title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Saving zip list to csv in Python
<p>How I can write below zip list to csv file in python?</p> <pre><code>[{'date': '2015/01/01 00:00', 'v': 96.5}, {'date': '2015/01/01 00:01', 'v': 97.0}, {'date': '2015/01/01 00:02', 'v': 93.75}, {'date': '2015/01/01 00:03', 'v': 96.0}, {'date': '2015/01/01 00:04', 'v': 94.5} </code></pre> <p>I have this error:</p> <pre><code>_csv.Error: sequence expected </code></pre> <p>My code is here:</p> <pre><code>import csv res = zip_list csvfile = "/home/stm/PycharmProjects/isbak_trafik/example.csv" with open(csvfile, "w") as output: writer = csv.writer(output, lineterminator='\n') writer.writerows(res) </code></pre>
1
NoSuchMethodException in MaxMind GeoIp dependency jackson-databind built with mvn shade
<p>I'm trying to run MaxMind's geoIP in a spark task, but I'm getting a NoSuchMethodException from a maxmind call to a jackson-databind library. I've removed all other versions of jackson-databind using mvn exclusions, yet the error persists after a mvn clean. What am I missing?</p> <p>No dependency conflicts: </p> <p><code>mvn dependency:tree -Dverbose -Dincludes=com.fasterxml.jackson.core:jackson-databind ... [INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ sift-etl --- [INFO] com.sift.etl:sift-etl:jar:0.1.6 [INFO] \- com.maxmind.geoip2:geoip2:jar:2.6.0:compile [INFO] \- com.maxmind.db:maxmind-db:jar:1.2.0:compile [INFO] \- com.fasterxml.jackson.core:jackson-databind:jar:2.7.0:compile </code></p> <p>Error:</p> <p><code>Exception in thread "main" java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.node.ArrayNode.&lt;init&gt;(Lcom/fasterxml/jackson/databind/node/JsonNodeFactory;Ljava/util/List;)V at com.maxmind.db.Decoder.decodeArray(Decoder.java:272) </code></p> <p>Edit: I have a ton of <code>org.codehaus.jackson</code>, do I need to exclude these as well? How can I resolve the differences in namespaces?</p> <p>Edit: This is built into a scala based project that runs in Apache Spark. The jar is compiled into a shaded jar using maven-shade-plugin 2.4</p> <p>Edit: Here's the complete output for jar tvf on the shaded jar: <a href="https://drive.google.com/file/d/0B2ZVKNsRXgTbeUdEU2ZhM2J3dmc/view?usp=sharing" rel="noreferrer">https://drive.google.com/file/d/0B2ZVKNsRXgTbeUdEU2ZhM2J3dmc/view?usp=sharing</a></p> <p>Here's the result of a grep for jackson-databind: <code> 0 Mon Jan 25 09:53:54 PST 2016 META-INF/maven/com.fasterxml.jackson.core/jackson-databind/ 151 Mon Jan 25 09:53:54 PST 2016 META-INF/maven/com.fasterxml.jackson.core/jackson-databind/pom.properties 5192 Mon Jan 25 09:53:54 PST 2016 META-INF/maven/com.fasterxml.jackson.core/jackson-databind/pom.xml </code></p> <p>and ArrayNode: <code>/usr/lib/jvm/sift-jdk1.8.0_66/bin/jar -tvf target/sift-etl-0.1.6-shaded.jar | grep ArrayNode 15060 Sat Jan 23 01:33:14 UTC 2016 shaded/parquet/org/codehaus/jackson/node/ArrayNode.class 1309 Sat Jan 23 01:33:18 UTC 2016 org/apache/lucene/index/DocumentsWriterDeleteQueue$QueryArrayNode.class 1645 Sat Jan 23 01:33:18 UTC 2016 org/apache/lucene/index/DocumentsWriterDeleteQueue$TermArrayNode.class 18145 Sat Jan 23 01:33:20 UTC 2016 com/fasterxml/jackson/databind/node/ArrayNode.class 1058 Sat Jan 23 01:33:22 UTC 2016 org/apache/commons/configuration/plist/XMLPropertyListConfiguration$ArrayNode.class </code></p> <p>Initializing and querying the maxmind GeoIP DB runs successfully in tests. The error only occurs in production when run as a spark task -- after it has been packaged using maven-shade.</p> <p>maven-shade plugin config: <a href="http://pastebin.com/QzrhM5Ee" rel="noreferrer">http://pastebin.com/QzrhM5Ee</a></p> <p>Is it meaningful that the shaded jar doesn't contain the jackson-databind jar, but all of the *.class files within the jar?</p>
1
DateTimePicker value from DataGridView
<p>I have some textboxes and a datetimepicker. There is also a datagridview on it. I upload data to a mysql table. I want to modify the data via textboxes and datetimepicker, but I get error:</p> <blockquote> <p>System.ArgumentOutOfRangeException</p> </blockquote> <p>on the dateTimePicker.Value row:</p> <pre><code>private void dataGridView1_SelectionChanged(object sender, EventArgs e) { dateTimePicker1.Value = Convert.ToDateTime(dataGridView1.SelectedRows[0].Cells[1].Value); idoTextBox.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); pkcomboBox.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString(); minositesbox.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString(); esetextBox.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString(); fotextBox.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString(); megjegyzestextBox.Text = dataGridView1.SelectedRows[0].Cells[7].Value.ToString(); } </code></pre> <p>What did I do wrong?</p>
1
Is there any easiest way to implement all required methods of protocol in iOS?
<p>First of all it's not the duplicate of <a href="https://stackoverflow.com/questions/1694325/xcode-possible-to-auto-create-stubs-for-methods-required-by-protocol-interface?rq=1">this question</a> because i couldn't find any discussion about offline documentation, suitable answers and about future release of updates in Xcode there.</p> <p>Actually I am from android and java background and currently starting to develop iOS apps too. As we all know we use to implement all methods of an <code>Interface</code> easily with the help of suggestions given in <strong>IDE</strong> by pressing <code>Alt + Enter</code>. </p> <p>And here in the iOS we have to see the reference each time and search for all required &amp; optional methods, and implement them manually one by one which consumes times It's fine for a moment But </p> <p><strong>My Questions are :</strong></p> <ol> <li>Is there Any easiest way to view all required method at first lookup in documentation OR implement all required methods of protocol with the help of IDE ?</li> <li>Is it possible that we will get this feature in future release of Xcode's update ? </li> <li>I can't be ensure availability of Internet all the time, And How can I see the documentation at that time ?</li> </ol>
1
Flatten aggregated key/value pairs from a JSONB field?
<p>I am working in Postgres 9.4 with the following table:</p> <pre class="lang-none prettyprint-override"><code> Column β”‚ Type β”‚ Modifiers ─────────────────┼──────────────────────┼────────────────────── id β”‚ integer β”‚ not null default practice_id β”‚ character varying(6) β”‚ not null date β”‚ date β”‚ not null pct_id β”‚ character varying(3) β”‚ total_list_size β”‚ double precision β”‚ not null star_pu β”‚ jsonb β”‚ </code></pre> <p>I have the following query:</p> <pre class="lang-sql prettyprint-override"><code>SELECT date, AVG(total_list_size) AS total_list_size, json_object_agg(key, val) AS star_pu FROM (SELECT date, SUM(total_list_size) AS total_list_size, key, SUM(value::numeric) val FROM frontend_practicelist p, jsonb_each_text(star_pu) GROUP BY date, key ) p GROUP BY date ORDER BY date; </code></pre> <p>It gives me results with a JSON object attached to <code>star_pu</code>:</p> <pre class="lang-none prettyprint-override"><code>date β”‚ 2013-04-01 total_list_size β”‚ 56025123.000000000000 star_pu β”‚ { &quot;antidepressants_cost&quot; : 180102416.8036909901975399, &quot;antiepileptic_drugs_cost&quot; : 296228344.171576079922216... } </code></pre> <p>Instead I would like to flatten the JSON result to a series of namespaced keys, so the result looks like this:</p> <pre class="lang-none prettyprint-override"><code>date β”‚ 2013-04-01 total_list_size β”‚ 56025123.000000000000 star_pu.antidepressants_cost β”‚ 180102416.8036909901975399 star_pu.antiepileptic_drugs_cost β”‚ 296228344.171576079922216 ... </code></pre> <p>Is this possible?</p>
1
Is there any way to schedule mail using gmail api?
<p>I am currently working gmail Queries of &quot;GTLGmail&quot; is there any way or query to schedule mails.</p> <p>I had gone through <a href="https://developers.google.com/gmail/api/guides" rel="nofollow noreferrer">https://developers.google.com/gmail/api/guides</a> but I am unable to find any solution for the same.</p>
1
getting json dictionary values, though python and jinja
<p>I have a dictionary in json that Im passing though into jinja using python. The page is not working not sure if this is the correct syntax</p> <pre><code>{% with open(jsonobject, 'r') as f json_data = json.load(f) for a, (b,c) in json_data.items() %} </code></pre> <p>--------------EDIT----------- This is a large dictionary within the json object being passed int which looks something like this</p> <pre><code>{"Dogs": [["spot"], 1], "Cats": [["whiskers"], 1], "fish": [["bubbles", "lefty", "tank", "goldie"], 4], "elephant": [["tiny", "spring"], 2], "zebra": [[], 1], "gazelle": [["red", "blue", "green", "yellow", "gold", "silver"], 6]} </code></pre>
1
Windows Server 2012 Memory Leak
<p>I have non-pool memory value about 3 Gb from total 6 Gb on windows server 2012. I think it's memory leak, see screens: <a href="https://i.stack.imgur.com/n1ysb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n1ysb.png" alt="enter image description here"></a></p> <p>Top process: <a href="https://i.stack.imgur.com/vFRrp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vFRrp.png" alt="enter image description here"></a></p> <p>Bamboo uses Microsoft Visual Studio 2013 to build project and run tests.</p> <ol> <li>How to determine bad process?</li> <li>And how to solve problem? May be it's possible to dispose this leak?</li> </ol>
1
perl+json getting size of an array
<p>I'm reading a json file in perl and having trouble using the results.</p> <p>I want to know how many views are present in the json file. there should be 2</p> <pre><code>my $data = decode_json($json); print Dumper($data); my @tmp=$data-&gt;{'views'}; my $nviews=scalar @tmp; print "nviews : $nviews\n"; </code></pre> <p>gives me</p> <pre><code>$VAR1 = { 'views' =&gt; [ { 'key' =&gt; 0, 'value' =&gt; { 'ptr_wrapper' =&gt; { 'data' =&gt; { 'width' =&gt; 776, 'height' =&gt; 1024, 'id_view' =&gt; 0, 'filename' =&gt; '000118800_15821618907.jpg', 'id_pose' =&gt; 0, 'id_intrinsic' =&gt; 13, 'local_path' =&gt; '/' }, 'id' =&gt; 2147483649 } } }, { 'key' =&gt; 1, 'value' =&gt; { 'ptr_wrapper' =&gt; { 'data' =&gt; { 'id_pose' =&gt; 1, 'id_intrinsic' =&gt; 11, 'filename' =&gt; '000132800_22050281512.jpg', 'id_view' =&gt; 1, 'local_path' =&gt; '/', 'width' =&gt; 850, 'height' =&gt; 1024 }, 'id' =&gt; 2147483650 } } } ] }; nviews : 1 </code></pre> <p>thanks in advance for any help.luc</p>
1
reset ng-model from controller in ng-repeat
<p>I am trying to create a list of editable inputs from a list of items. I want the user to be able to edit any of the items, but if they change there mind they can click a button and reset it back to the way it was. </p> <p>So far I have everything working except the reset.</p> <p>my html</p> <pre><code>&lt;div ng-app ng-controller="TestController"&gt; &lt;div ng-repeat="item in list"&gt; &lt;label&gt;Input {{$index+1}}:&lt;/label&gt; &lt;input ng-model="item.value" type="text" ng-click="copy(item)"/&gt; &lt;button ng-click="reset(item)"&gt; x &lt;/button&gt; &lt;/div&gt; {{list}}&lt;br&gt; {{selected_item_backup}} &lt;/div&gt; </code></pre> <p>my controller</p> <pre><code>function TestController($scope) { $scope.selected_item_backup = {}; $scope.list = [ { value: 'value 1' }, { value: 'value 2' }, { value: 'value 3' } ]; $scope.reset = function (item) { // i know this wont work for many reasons, it is just an example of what I would like to do item = $scope.selected_item_backup; }; $scope.copy = function (item) { angular.copy(item, $scope.selected_item_backup); }; } </code></pre> <p>and here is a fiddle <a href="http://jsfiddle.net/ryanmc/1ab24o4t/1/" rel="nofollow">http://jsfiddle.net/ryanmc/1ab24o4t/1/</a></p> <p>Keep in mind that this is a simplified version of my real code. My objects will have many editable fields each. Also they are not indexed, and so the index cannot be relied on. I just want to be able to assign the original item on top of the new and have it replaced.</p>
1
VueJS Select2 directive doesn't fire @change event
<p>As title says, I registered Select2 directive for VueJS 1.0.15 using example from their page. I want to catch @change event but it doesn't work.</p> <p>HTML:</p> <pre><code>&lt;select v-select="item.service" :selected="item.service" @change="serviceChange(item)"&gt; &lt;option value="1"&gt;test 1&lt;/option&gt; &lt;option value="2"&gt;test 2&lt;/option&gt; &lt;/select&gt; </code></pre> <p>JS:</p> <pre><code>Vue.directive('select', { twoWay: true, params: ['selected'], bind: function () { var self = this $(this.el) .select2({ minimumResultsForSearch: Infinity }) .val(this.params.selected) .on('change', function () { console.log('changed'); self.set(this.value); }) }, update: function (value) { $(this.el).val(value).trigger('change') }, unbind: function () { $(this.el).off().select2('destroy') } }); var Checkout = new Vue({ el: '.Checkout', methods: { serviceChange: function (item) { console.log(item); }, } }); </code></pre>
1
Bootstrap tabs - Next & previous Buttons
<p>I am using Bootstrap 3.4.</p> <p>I am using tab-pills on a form with 3 tabs.</p> <p>I am trying to place next &amp; previous buttons to aid navigation between the tab form.</p> <p>I have read this <a href="https://stackoverflow.com/questions/22297964/bootstrap-tabs-next-previous-buttons-for-forms">post</a> on the topic (and the <a href="http://www.bootply.com/120472" rel="nofollow noreferrer">bootply</a>), which is exactly what I require, and I applied the necessary code.</p> <p>On my form, in all 3 tabs, I always see the next1 button, I never see the other buttons.</p> <p>I finally figured out that the error is to do with the class=active on the <code>&lt;li class="active"&gt;</code> line of code> (or at least I am almost certain this is the error).</p> <p>I have searched Google and SO to figure out how to get the js code working, but I cannot figure out to correct this simple issue. I have exhausted all my attempts, so I turn to SO for assistance.</p> <p><strong>Can anyone suggest how I might correct this?</strong></p> <p>Here is my js code:</p> <pre><code>$('.btnNext').click(function(){ $('.nav-pills &gt; .active').next('li').find('a').trigger('click'); }); $('.btnPrevious').click(function(){ $('.nav-pills &gt; .active').prev('li').find('a').trigger('click'); }); </code></pre> <p>Here is my HTML code:</p> <pre><code>&lt;ul class="nav nav-pills"&gt; &lt;li class="active"&gt; &lt;a data-toggle="tab" id="id_link_tab1" href="#tab1"&gt; &lt;i class="fa fa-check-square-o icon_size26"&gt;&lt;/i&gt; &amp;nbsp;Tab #1 &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a data-toggle="tab" id="id_link_tab2" href="#tab2"&gt; &lt;i class="fa fa-file-text icon_size26"&gt;&lt;/i&gt; &amp;nbsp;Tab #2 &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a data-toggle="tab" id="id_link_tab3" href="#tab3"&gt; &lt;i class="fa fa-pencil-square-o icon_size26"&gt;&lt;/i&gt; &amp;nbsp;Tab #3 &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div class="tab-content"&gt; &lt;div class="tab-pane active" id="tab1"&gt; &lt;a class="btn btn-primary btnNext"&gt;Next1&lt;/a&gt; &lt;/div&gt; &lt;div class="tab-pane" id="tab2"&gt; &lt;a class="btn btn-primary btnNext"&gt;Next2&lt;/a&gt; &lt;a class="btn btn-primary btnPrevious"&gt;Previous3&lt;/a&gt; &lt;/div&gt; &lt;div class="tab-pane" id="tab3"&gt; &lt;a class="btn btn-primary btnPrevious"&gt;Previous4&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
1
Converting String to Integer in Visual Basic
<p>How can you convert string to integer?</p> <p>I use <strong>Visual Basic 2008 Express Edition</strong></p>
1
How to checkout files from another branch and then overwrite the current branch
<p>Based on <a href="http://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/" rel="nofollow">http://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/</a>, we can use the following command to merge changes from another branch to local branch.</p> <p>For example:</p> <pre><code>$git checkout master -- hello.c </code></pre> <p>This command will merge the hello.c from master branch to current local branch.</p> <p>Question> What if I want to use the hello.c from master to overwrite my local branch file without any merge? which option I should use?</p> <p>Thank you</p> <p>-- Update --</p> <pre><code>$ pwd /sandbox/projectOne $ git branch feature/F_Source * feature/F_Dest master $ git status -s $ $ git diff feature/F_Source feature/F_Dest -- Messages/src/Hello.C | wc -l 165 $ git checkout feature/F_Source -- Messages/src/Hello.C $ $ git diff feature/F_Source feature/F_Dest -- Messages/src/Hello.C | wc -l 165 $ git status -s M Messages/src/Hello.C $ </code></pre> <p>As you can see, before the checkout, there is a difference between F_Source Hello.C and F_Dest Hello.C. After the checkout, there is still a difference. So I assume the checkout is NOT a overwrite operation otherwise we should not see any difference.</p>
1
Creating match rooms with firebase
<p>Im building a game where some k number of people can play, live</p> <p>Im using firebase for sharing user-related data and obtaining updates from a backend nodeJS on heroku. So far so good, but I have one major requirement that I havent yet fully figured out to build using firebase and a NodeJS backend</p> <p>There could be potentially a large number of users wanting a play a game. I'd like to match k of these users and assign them a unique gameroom id, where they can then 'play' . For the sake of this question we can omit what the actual 'play' is.</p> <p>So I'd like to create a random set of k users and here is how Im thinking of approaching it, I'd like to know if this is a good approach or a terrible approach. I'd also like more suggestions if there is an easier way to achieve this:</p> <ol> <li>Live players indicate on my Firebase store that they'd like to play using a state variable</li> <li>A NodeJS backend on Heroku runs every few seconds to ensure that the system has a good 'mix' of players. When it runs, it uses the <a href="https://www.firebase.com/docs/rest/api/" rel="nofollow">Firebase REST API</a> to pull up <em>all</em> the waiting Live players (is this a good idea?)</li> <li>It then sections off these live players to a <a href="https://github.com/firebase/firebase-queue" rel="nofollow">Firebase Queue</a>. It does this by taking 1000*k live users and creating 1 task. Thus it may create many such tasks with 1000*k users in each task.</li> </ol> <p>I'd like to add that if there was a way for a single queue worker to access multiple tasks then I would much prefer that. In that case Step 2 is pretty much not required, since the live players can add themselves to the queue and a single worker can access k of these users to match them together - is this possible with the current Firebase Queue??</p> <ol start="4"> <li>Queue workers pick up a task and make 1000 matches and write these match details in the players node in firebase</li> <li>Players waiting on their node are now matched with a unique gameroom id and k other players</li> </ol>
1
Why is DataTables render function called 3 times?
<p>I am using DataTables 1.10.9, with client-side processing.</p> <p>I am using the 'ajax' option to retrieve the data for the DataTable.</p> <p>I have put a small console.log(renderCount) in the '<strong>render</strong>' function.</p> <p>There are 4,921 rows in the table.</p> <p>However, the console shows that the render function is being called a total of 14,772 times! </p> <p>(14,772 = number of rows * 3 + 11)</p> <p>I believe this would be slowing down the rendering process.</p> <p>What's more - I have the '<strong>deferRender</strong>' option set - so I would have thought that the render function should only be called 10 times, which is the default page size.</p> <p>Whats going on?</p> <p><strong>Besides server-side processing</strong> - how can I improve the initial rendering performance for this table???</p> <p>Here is an example of one row's data:</p> <pre><code>{ Id: 1, Type: "Purchases", LifecycleStatus: "Manual", ReceivedAtLocal: "04/02/2016 20:45:16", ModifiedAtLocal: "04/02/2016 21:45:16", Operator: "a-mjohn", PartNumber: "IXAWGCAUNVJHONP" } </code></pre> <p>Here is the table definition code:</p> <pre><code> var renderCount = 0; transactionTable = $("#tblTransactions").DataTable({ "searchDelay" : 500, "bDestroy": true, "ajax": window.getTransactionDataUrl, "processing": false, "deferRender" : true, "columns": [ { 'render': function (data, type, full, meta){ // Other code omitted for brevity renderCount++; console.log(renderCount); return ""; }, "bSortable": false }, { 'render': function (data, type, full, meta) { return '&lt;input type="checkbox"&gt;'; }, "bSortable": false }, { "data": "Id" }, { "data": "Type" }, { "data": "LifecycleStatus" }, { "data": "Operator" }, { "data": "PartNumber" }, { "data": "ReceivedAtLocal" }, { "data": "ModifiedAtLocal" }, { "defaultContent": "&lt;button class='btn btn-primary btn-xs' data-toggle='modal' data-target='#detailsModal'&gt;Details&lt;/button&gt;", "bSortable": false }, { "defaultContent": "&lt;button class='btn btn-primary btn-xs' data-toggle='modal' data-target='#auditModal'&gt;Audit&lt;/button&gt;", "bSortable": false }, { "defaultContent": "&lt;button class='btn btn-primary btn-xs' data-toggle='modal' data-target='#commentModal'&gt;Comments&lt;/button&gt;", "bSortable": false } ], "rowId": "Id", 'order': [[7, "asc"]], 'rowCallback': function (row, data, dataIndex) { // Get row ID var rowId = data["Id"]; if ($.inArray(rowId, window.transIndexPage.rows_selected) !== -1) { $(row).find('input[type="checkbox"]').prop("checked", true); $(row).addClass("selected"); } } }); </code></pre>
1
HTTP BASIC Authentication logout issue with Chrome
<p>I am using this below method to logout from the HTTP server which is using Basic HTTP authentication. This work fine with IE and FireFox . But in case of Chrome , I am able to get the html file even with the wrong user name and password.</p> <p>In Chrome , the flow is , I am getting "********** Failed ***********" error then the requested page(some_server_file.html) is shown.</p> <p>But in IE/Chrome , the flow is , I am getting "********** Failed ***********" error then login dialog is prompting for the credentails.</p> <p>Someway , Chrome is sending the correct user name and password even after the first request failed with the wrong credentails.</p> <p>Can anyone fix the Chrome issue?</p> <pre><code>function logout() { jQuery.ajax({ type: "get", url: "some_server_file.html", async: false, username: "wronguser", password: "wrongpass", headers: {"Authorization": "Basic xxx"} }) .success(function () { console.log("********** Success ***********"); }) .fail(function () { console.log("********** Failed ***********"); }); return false; } </code></pre> <p>Thx</p>
1
Kendo UI - JSON Response for - Grid using Remote Data Source W/Server Grouping & Server Aggregates
<p>I have a project in which I'm using the KendoUI Grid using the server to get the data instead of locally.</p> <p>I'm not sure what the JSON response should be from my server to get grouping to work however. My goal is when the user drags a column to the grouping header that I know what kind of JSON response to give back so the GRID groups by that column and any other columns that might be added to that header.</p> <p><a href="https://i.stack.imgur.com/odNv6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/odNv6.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/Ce5MY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ce5MY.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/fblNh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fblNh.png" alt="enter image description here"></a></p> <p>Given the image above, how do I create a JSON response to fulfill it (so its showing what its supposed to grouped)? <strong>I get I have to do this on my own on the server</strong> but not sure how <strong>JSON needs to be formated</strong>. Furthermore if I want to show a 'count' field next to the groups when they are created so I know how many items are in each group (which I believe is the aggregate?)</p> <p>My current grid codes looks like the following:</p> <pre><code>&lt;div id="grid" style="height:100%;"&gt;&lt;/div&gt; &lt;script&gt; $(window).on("resize", function() { kendo.resize($("#grid")); }); var crudServiceBaseUrl = "/api", dataSource = new kendo.data.DataSource({ transport: { read: { url: crudServiceBaseUrl + "/companies", dataType: "json", type: "POST" }, update: { url: crudServiceBaseUrl + "/companies/update", dataType: "json", type: "POST" }, destroy: { url: crudServiceBaseUrl + "/companies/destroy", dataType: "json", type: "POST" }, create: { url: crudServiceBaseUrl + "/companies/create", dataType: "json", type: "POST" }, parameterMap: function(options, operation) { if (operation !== "read" &amp;&amp; options.models) { return {models: kendo.stringify(options.models)}; } } }, error: function (e) { /* the e event argument will represent the following object: { errorThrown: "custom error", errors: ["foo", "bar"] sender: {... the Kendo UI DataSource instance ...} status: "customerror" xhr: null } */ //alert("Status: " + e.status + "; Error message: " + e.errorThrown); console.log("Status: " + e.status + "; Error message: " + e.errorThrown); console.log("Errors: " + e.errors.join("; ")); }, autoSync: false, serverPaging: true, serverFiltering: true, serverSorting: true, serverGrouping: true, serverAggregates: true, pageSize: 20, columnResizeHandleWidth: 6, schema: { total: "itemCount", data: "items", groups: "groups", aggregates: "aggregates", group: { field: "phone", aggregates: [{ field: "phone", aggregate: "count" }] }, model: { id: "id", fields: { id: { editable: false, nullable: true }, name: { validation: { required: true } }, phone: { type: "string", validation: { required: true, phonerule: function(e){ if (e.is("[data-phonerule-msg]")) { var input = e.data('kendoMaskedTextBox'); //If we reached the end of input then it will return -1 which means true, validation passed //Otherwise it won't === -1 and return false meaning all the characters were not entered. return input.value().indexOf(input.options.promptChar) === -1; } return true; //return true for anything else that is not data-phonerule-msg } } }, email: { type: "string", validation: { required: true, email:true } } } } } }); $("#grid").kendoGrid({ dataSource: dataSource, groupable: true, sortable: { mode: "multiple", allowUnsort: true }, selectable: "multiple cell", allowCopy:true, toolbar: ["create","excel"], excel: { fileName: "Kendo UI Grid Export.xlsx", //Below is only used as fallback for old browsers without support proxyURL: "//demos.telerik.com/kendo-ui/service/export", filterable: true }, pageable: { refresh: true, pageSizes: true, buttonCount: 5 }, reorderable: true, resizable: true, columnMenu: true, filterable: true, editable: "popup", mobile: true, columns: [ { field: "name", title: "Company Name", aggregates: ["count"], groupFooterTemplate: "Count: #=count#" }, { field: "phone", title: "Phone", editor: function(container, options){ //pattern="[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}" var input = $('&lt;input type="tel" data-phonerule-msg="Invalid Phone Number!" class="k-textbox" required /&gt;'); input.attr("name", options.field); input.kendoMaskedTextBox({ mask: "(999) 000-0000" }); input.appendTo(container); }, aggregates: ["count"], groupFooterTemplate: "Count: #=count#" }, { field: "email", title: "Email", editor: function(container, options){ var input = $('&lt;input type="email" data-email-msg="Invalid email!" class="k-textbox" required/&gt;'); input.attr("name", options.field); input.appendTo(container); }, aggregates: ["count"], groupFooterTemplate: "Count: #=count#" }, { command: ["edit", "destroy"], title: "Operations", width: "240px" } ], }); &lt;/script&gt; </code></pre> <p>My current code that generates the demo javascript via Symfony 3.0 is below in..</p> <p><strong>DefaultController.php</strong></p> <pre><code>/** * @Route("/api/companies", name="api_companies_read") */ public function apiCompaniesReadAction(Request $request) { $data["itemCount"] = "7"; // $tdata["field"] = ""; // $tdata["value"] = ""; // $tdata["items"] = "hey"; // $data["groups"][] = $tdata; $tdata["id"] = "1"; $tdata["name"] = "Joe"; $tdata["phone"] = "(714)475-8651"; $tdata["email"] = "[email protected]"; $data["items"][] = $tdata; $tdata["id"] = "2"; $tdata["name"] = "Rachel"; $tdata["phone"] = "(563)812-4184"; $tdata["email"] = "[email protected]"; $data["items"][] = $tdata; $tdata["id"] = "3"; $tdata["name"] = "John"; $tdata["phone"] = "(563)812-4184"; $tdata["email"] = "[email protected]"; $data["items"][] = $tdata; $tdata["id"] = "4"; $tdata["name"] = "Richard"; $tdata["phone"] = "(563)812-4184"; $tdata["email"] = "[email protected]"; $data["items"][] = $tdata; $tdata["id"] = "5"; $tdata["name"] = "Sister"; $tdata["phone"] = "(563)812-4184"; $tdata["email"] = "[email protected]"; $data["items"][] = $tdata; $tdata["id"] = "6"; $tdata["name"] = "Brother"; $tdata["phone"] = "(563)812-4184"; $tdata["email"] = "[email protected]"; $data["items"][] = $tdata; $tdata["id"] = "7"; $tdata["name"] = "Sibling"; $tdata["phone"] = "(563)812-4184"; $tdata["email"] = "[email protected]"; $data["items"][] = $tdata; // schema: { // total: "total", // model: { // id: "CompanyID", // fields: { // CompanyID: { editable: false, nullable: true }, // Name: { validation: { required: true } }, // Phone: { type: "string" }, // Email: { type: "string" } // } // } // } // replace this example code with whatever you need return new JsonResponse($data); } </code></pre> <p>The current JSON it creates looks like this.</p> <p><strong>JSON</strong></p> <pre><code>{"itemCount":"7","items":[{"id":"1","name":"Joe","phone":"(714)475-8651","email":"[email protected]"},{"id":"2","name":"Rachel","phone":"(563)812-4184","email":"[email protected]"},{"id":"3","name":"John","phone":"(563)812-4184","email":"[email protected]"},{"id":"4","name":"Richard","phone":"(563)812-4184","email":"[email protected]"},{"id":"5","name":"Sister","phone":"(563)812-4184","email":"[email protected]"},{"id":"6","name":"Brother","phone":"(563)812-4184","email":"[email protected]"},{"id":"7","name":"Sibling","phone":"(563)812-4184","email":"[email protected]"}]} </code></pre> <p>I found an article <a href="http://www.telerik.com/forums/datasource-remote-grouping" rel="nofollow noreferrer">here</a> that looks close to what I want just hard to understand. <a href="http://docs.telerik.com/KENDO-UI/api/javascript/data/datasource#configuration-schema.groups" rel="nofollow noreferrer">This</a> might also help.</p> <p>I created <a href="https://jsfiddle.net/x11joex11/zz3jfp20/15/" rel="nofollow noreferrer">JSFiddle</a> that can be played around with, just needs to be supplied valid data.</p> <p><strong>Update</strong></p> <p>I got server paging to work! The first major change is on the transport for the datasource you have to change the parameterMap to send json so you can access what its trying to tell your server to change.</p> <pre><code>dataSource = new kendo.data.DataSource({ transport: { read: { url: crudServiceBaseUrl + "/companies", dataType: "json", type: "POST" }, update: { url: crudServiceBaseUrl + "/companies/update", dataType: "json", type: "POST" }, destroy: { url: crudServiceBaseUrl + "/companies/destroy", dataType: "json", type: "POST" }, create: { url: crudServiceBaseUrl + "/companies/create", dataType: "json", type: "POST" }, parameterMap: function(options, operation) { return kendo.stringify(options); } }, </code></pre> <p>My datasource looks like above, but you could adjust to your needs. Next my php file below.</p> <p><strong>PHP</strong> <strong>/companies</strong></p> <pre><code>/** * @Route("/api/companies", name="api_companies_read") */ public function apiCompaniesReadAction(Request $request) { $request_body = file_get_contents('php://input'); $json = json_decode($request_body); //Based on the JSON Payload response adjust the search in the database if($json){ $page = $json-&gt;page; $pageSize = $json-&gt;pageSize; $skip = $json-&gt;skip; $take = $json-&gt;take; }else{ $page = 1; $pageSize = 20; $skip = 1; $take = 1; } $repository = $this-&gt;getDoctrine()-&gt;getRepository('AppBundle:Company'); /* findBy( array $criteria, array $orderBy = null, integer|null $limit = null, integer|null $offset = null ) */ $company_total = $repository-&gt;findAll(); $company_records = $repository-&gt;findBy(array(),array(),$pageSize,($page-1)*$pageSize); $data["total"] = count($company_total); foreach($company_records as $company){ $temp["id"] = $company-&gt;getId(); $temp["name"] = $company-&gt;getName(); $temp["phone"] = $company-&gt;getPhone(); $temp["email"] = $company-&gt;getEmail(); $data["data"][] = $temp; } //converts data to JSON return new JsonResponse($data); } </code></pre> <p>Please remember the above is a Symfony 3.0 php implementation using annotations to set the route. The important part in that code is.</p> <pre><code>$request_body = file_get_contents('php://input'); $json = json_decode($request_body); //Based on the JSON Payload response adjust the search in the database if($json){ $page = $json-&gt;page; $pageSize = $json-&gt;pageSize; $skip = $json-&gt;skip; $take = $json-&gt;take; }else{ $page = 1; $pageSize = 20; $skip = 1; $take = 1; } </code></pre> <p>The <code>file_get_contents('php://input');</code> gets the javascript object that the KendoUI control sends back.</p> <p><strong>UPDATE # 3 Got Server Sorting Working!</strong></p> <p>Below is an example implementaiton using Symfony 3.0 and Doctrine to do Server Sorting!</p> <p><strong>PHP</strong></p> <pre><code>/** * @Route("/api/companies", name="api_companies_read") */ public function apiCompaniesReadAction(Request $request) { $request_body = file_get_contents('php://input'); $json = json_decode($request_body); //print_r($json); //default parameters in case of error. $page = 1; $pageSize = 20; $skip = 1; $take = 1; $sort = array(); //Based on the JSON Payload response adjust the search in the database if(isset($json)){ $page = $json-&gt;page; $pageSize = $json-&gt;pageSize; $skip = $json-&gt;skip; $take = $json-&gt;take; if(isset($json-&gt;sort)){ //"sort":[{"field":"name","dir":"asc"}]}: foreach($json-&gt;sort as $sortObj){ $sort[$sortObj-&gt;field] = $sortObj-&gt;dir; } } } $repository = $this-&gt;getDoctrine()-&gt;getRepository('AppBundle:Company'); /* findBy( array $criteria, array $orderBy = null, integer|null $limit = null, integer|null $offset = null ) */ $company_total = $repository-&gt;findAll(); $company_records = $repository-&gt;findBy(array(),$sort,$pageSize,($page-1)*$pageSize); $data["total"] = count($company_total); foreach($company_records as $company){ $temp["id"] = $company-&gt;getId(); $temp["name"] = $company-&gt;getName(); $temp["phone"] = $company-&gt;getPhone(); $temp["email"] = $company-&gt;getEmail(); $data["data"][] = $temp; } //converts data to JSON return new JsonResponse($data); } </code></pre>
1
SNMP: How many OIDs can be requested in one PDU?
<p>A simple question that I can not find answer to.</p> <p>I know that a GET request can be sent with multiple OIDs in PDU. How many OIDs maximum can be requested in one PDU in one request? Is there a limit in SNMP? in UDP?</p>
1
Vuejs not prompting bootstrap popover
<p>I am using <code>bootstrap popover</code> with <code>vuejs</code>.</p> <p>How can I trigger <code>vue</code> functionality? </p> <p>In below code when I am clicking on <code>add break</code> link, it opens <code>bootstrap popover</code>, with <code>click me</code> button. Now here <code>vuejs</code> doesn't work, if I click on <code>click me</code>, it is not prompting alert.</p> <pre><code>&lt;a data-toggle="popover" data-placement="top" v-d2d-popover data-content='&lt;button v-on:click="alert(6)"&gt;click me&lt;/button&gt;' href="javascript:void(0)" class="btn btn-link popover-notitle"&gt; &lt;i class="ace-icon fa fa-plus-circle bigger-120 green"&gt;&lt;/i&gt;add break &lt;/a&gt; </code></pre> <p>Can anybody help me?</p>
1
Jersey 2: render Swagger static content correctly without trailing slash(/)
<p>What I did is to use <code>Grizzly</code>/<code>Jersey</code> to host <code>swagger-ui</code>, which is static content.</p> <p>Here's part of <code>build.gradle</code>:</p> <pre><code>compile 'org.glassfish.jersey.core:jersey-server:2.22.1' compile 'org.glassfish.jersey.containers:jersey-container-grizzly2-http:2.22.1' compile 'org.glassfish.jersey.containers:jersey-container-grizzly2-servlet:2.22.1' </code></pre> <p>Here's how to configure static content with <code>Grizzly</code>:</p> <pre><code>httpServer = GrizzlyWebContainerFactory.create(uri); httpServer.getServerConfiguration().addHttpHandler(new StaticHttpHandler("swagger-ui"), "/swagger"); </code></pre> <p><code>swagger-ui</code> is the folder under the project root folder.</p> <p><strong>Everything is fine when I access <code>http://localhost/swagger/</code></strong> but when I try <code>http://localhost/swagger</code>, it only gives a simple page without rendering, which seems all css/js files are missing: <a href="https://i.stack.imgur.com/JTxlu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JTxlu.png" alt="enter image description here"></a></p> <p>I'm wondering what's the best way to make url without trailing slash(/) to be the same as those with trailing slash.</p> <p>Update: I've raised a ticket to swagger-ui: <a href="https://github.com/swagger-api/swagger-ui/issues/1966" rel="nofollow noreferrer">https://github.com/swagger-api/swagger-ui/issues/1966</a> but it said it's a configuration problem with <code>Grizzly</code> so another ticket for <code>Grizzly</code>: <a href="https://java.net/jira/browse/GRIZZLY-1823" rel="nofollow noreferrer">https://java.net/jira/browse/GRIZZLY-1823</a></p> <p>No solution found now. I'm thinking to use another web server.</p>
1
"Total rows" in custom Power BI visualizations
<p>I have a question about creating the <a href="https://github.com/Microsoft/PowerBI-visuals" rel="nofollow noreferrer">custom visualization</a> in Power BI.</p> <p>I want to implement a "total row" functionality which is available in the built-in matrix visualization. The main concept is to automatically sum-up every value and group it by the rows. This is how it's looks like on the matrix visualization: <a href="https://i.stack.imgur.com/rt1XZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rt1XZ.png" alt="Built-in matrix &quot;total rows&quot; functionality"></a></p> <p>But, to be honest, I don't know how to achieve this. I try different things but I can't receive this grouped values in the dataViews.</p> <p>I tried to analyze the built-in <a href="https://github.com/Microsoft/PowerBI-visuals/blob/master/src/Clients/Visuals/visuals/matrix.ts" rel="nofollow noreferrer">matrix.ts code</a> but it's quite different that the custom visualizations code. I found the <a href="https://github.com/Microsoft/PowerBI-visuals/blob/master/src/Clients/Visuals/visuals/matrix.ts#L918" rel="nofollow noreferrer">customizeQuery</a> method which set the subtotalType property to the rows and columns - I tried to add this in my code but I don't see any difference in the dataViews (I don't found the grouped value).</p> <p>Currently my capabilities.dataViewMappings is set like this:</p> <pre><code> dataViewMappings: [ { conditions: [ { 'Rows': { max: 3 } } ], matrix: { rows: { for: { in: 'Rows' }, }, values: { for: { in: 'Values' } }, }, } ] </code></pre> <p>Does anyone know how we could achieve this "total row" functionality?</p> <p><strong>UPDATE 1</strong></p> <p>I already found the solution: when we implement the <code>customizeQuery</code> method (in the same way as the <a href="https://github.com/Microsoft/PowerBI-visuals/blob/master/src/Clients/Visuals/visuals/matrix.ts#L918" rel="nofollow noreferrer">customizeQuery</a> method in the matrix.ts code), and then add the reference to it in the <code>powerbi.visuals.plugins.[visualisationName+visualisationAddDateEpoch].customizeQuery</code> then it works as expected (I receive in the <code>dataViews[0].matrix.row.root</code> children elements that has the total values from row).</p> <p>The only problem now is that I don't know exactly how to add correctly this reference to the <code>customizeQuery</code> method. For example the <code>[visualisationName+visualisationAddDateEpoch]</code> is <code>Custom1451458639997</code>, and I don't know what those number will be (I know only the name). I created the code in my visualisation constructor as below (and it's working):</p> <pre><code> constructor() { var targetCustomizeQuery = this.constructor.customizeQuery; var name = this.constructor.name; for(pluginName in powerbi.visuals.plugins) { var patt = new RegExp(name + "[0-9]{13}"); if(patt.test(pluginName)) { powerbi.visuals.plugins[pluginName].customizeQuery = targetCustomizeQuery; break; } } } </code></pre> <p>But in my opinion this code is very dirty and inelegant. I want to improve it - what is the correct way to tell the Power BI that we implement the custom <code>customizeQuery</code> method and it should use it?</p> <p><strong>UPDATE 2</strong></p> <p>Code from <strong>update 1</strong> works only with the Power BI in the web browser (web based). On the Power BI Desktop the <code>customizeQuery</code> method isn't invoked. What is the correct way to tell the Power BI to use our custom <code>customizeQuery</code> method? In the code from <a href="https://github.com/Microsoft/PowerBI-visuals" rel="nofollow noreferrer">PowerBI-visuals repository</a> using PowerBIVisualPlayground we could declare it in the <a href="https://github.com/Microsoft/PowerBI-visuals/blob/master/src/Clients/Visuals/plugins.ts#L258" rel="nofollow noreferrer"><code>plugin.ts</code></a> file (in the same way like the matrix visual is done):</p> <pre><code>export let matrix: IVisualPlugin = { name: 'matrix', watermarkKey: 'matrix', capabilities: capabilities.matrix, create: () =&gt; new Matrix(), customizeQuery: Matrix.customizeQuery, getSortableRoles: (visualSortableOptions?: VisualSortableOptions) =&gt; Matrix.getSortableRoles(), }; </code></pre> <p>But, in my opinion, from the Power BI Dev Tools we don't have access to add additional things to this part of code. Any ideas?</p>
1
Find the most frequent k-mers with mismatches in a DNA string
<p>I am trying to solve finding the most frequent k-mers with mismatches in a string. The requirements are listed below:</p> <p>Frequent Words with Mismatches Problem: Find the most frequent k-mers with mismatches in a string.</p> <p>Input: A string Text as well as integers k and d. (You may assume k ≀ 12 and d ≀ 3.)</p> <p>Output: All most frequent k-mers with up to d mismatches in Text.</p> <p>Here is an example: </p> <p>Sample Input:</p> <p>ACGTTGCATGTCGCATGATGCATGAGAGCT</p> <p>4 1</p> <p>Sample Output:</p> <p>GATG ATGC ATGT</p> <p>The simplest and most inefficient way is to list all of k-mers in the text and calculate their hamming_difference between each other and pick out patterns whose hamming_difference less than or equal with d, below is my code:</p> <pre><code>kmer = 4 in_genome = "ACGTTGCATGTCGCATGATGCATGAGAGCT"; in_mistake = 1; out_result = []; mismatch_list = [] def hamming_distance(s1, s2): # Return the Hamming distance between equal-length sequences if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal length") else: return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) for i in xrange(len(in_genome)-kmer + 1): v = in_genome[i:i + kmer] out_result.append(v) for i in xrange(len(out_result)): for j in xrange(i + 1, len(out_result)): if hamming_distance((out_result[i], out_result[j]) &lt;= in_mistake: mismatch_list.append(out_result[i], out_result[j]) print mismatch_list </code></pre> <p>When I ran the code it always showed "Invalid syntax" and pointed out the error is from the ":" of "if hamming_distance((out_result[i], out_result[j]) &lt;= in_mistake: ". It could have more errors even I figure out this one. Does anyone know what happened?</p> <p>Another thing is I know there definitely exists better algorithms. Any clues?</p>
1
Adding a empty XMLAttribute in a XMLElement on Oracle SQL
<p>I need to create an XML file with some elements that have some attributes, some of which are null. I just want to let the null attributes be visible in the XML file.</p> <p>An example query is:</p> <pre><code> SELECT XMLElement("PropertySet", XMLATTRIBUTES('TEST' AS "OrderId", '' AS "DHLCode") FROM DUAL AS RESULT </code></pre> <p>Which produces: </p> <pre><code>&lt;PropertySet OrderId= "TEST" &gt; &lt;\PropertySet&gt; </code></pre> <p>But I need something like</p> <pre><code>&lt;PropertySet OrderId= "TEST" DHLCode = "" &gt;&lt;\PropertySet&gt; </code></pre> <p>How can I achieve this result?</p>
1
alarm clock like sleep cycle ios swift
<p>I have been looking for answer very long and I haven't found it. I'd like to create some app which would be similar to alarm clock. </p> <p>One of it's features will be waking up at specified by the user time (nothing surprising). If you look at sleep cycle app, you would notice that it wakes you up but it also track your sleep, so it has to be running at background. Moreover it also can play song which wakes you up until you turn it off (not only for 30 seconds, as the limit of length of notification sound). It also can turn up the volume of device. </p> <p>If I haven't seen this app at action I wouldn't believe that such a functionality is possible on iPhone to do by developers.</p> <p>My current progress:</p> <ol> <li><p>I can play the sound at time specified by user but only if the app is in foreground. If sound is played and then user click home button sound is still played (that is cool) but the music can't start if the app is in background. This is some code:</p> <pre><code>do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers) print("AVAudioSession Category Playback OK") do { try AVAudioSession.sharedInstance().setActive(true) print("AVAudioSession is Active") } catch let error as NSError { print(error.localizedDescription) } } catch let error as NSError { print(error.localizedDescription) }</code></pre> <p>and then I use <pre><code>AVAudioPlayer</code></pre> to play some sound. So the first question is: how to play that sound from background like sleep cycle app does? And I'm sure that sleep cycle doesn't use notification sound.</p></li> </ol> <p>And my second question is how to change device volume (sleep cycle also can do it but on the stack overflow there are many people saying that it is impossible).</p> <p>Please help :)</p>
1
Why Stanford parser with nltk is not correctly parsing a sentence?
<p>I am using Stanford parser with nltk in python and got help from <a href="https://stackoverflow.com/questions/13883277/stanford-parser-and-nltk">Stanford Parser and NLTK</a> to set up Stanford nlp libraries.</p> <pre><code>from nltk.parse.stanford import StanfordParser from nltk.parse.stanford import StanfordDependencyParser parser = StanfordParser(model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz") dep_parser = StanfordDependencyParser(model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz") one = ("John sees Bill") parsed_Sentence = parser.raw_parse(one) # GUI for line in parsed_Sentence: print line line.draw() parsed_Sentence = [parse.tree() for parse in dep_parser.raw_parse(one)] print parsed_Sentence # GUI for line in parsed_Sentence: print line line.draw() </code></pre> <p>I am getting wrong parse and dependency trees as shown in the example below, it is treating 'sees' as noun instead of verb.</p> <p><a href="https://i.stack.imgur.com/I3hSv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I3hSv.png" alt="Example parse tree"></a> <a href="https://i.stack.imgur.com/C6gL8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C6gL8.png" alt="Example dependency tree"></a></p> <p>What should I do? It work perfectly right when I change sentence e.g.(one = 'John see Bill'). The correct ouput for this sentence can be viewed from here <a href="https://stackoverflow.com/questions/10401076/difference-between-constituency-parser-and-dependency-parser">correct ouput of parse tree</a></p> <p>Example of correct output is also shown below:</p> <p><a href="https://i.stack.imgur.com/68vBR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/68vBR.png" alt="correctly parsed"></a></p> <p><a href="https://i.stack.imgur.com/evbZ8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/evbZ8.png" alt="correct dependency parsed tree"></a></p>
1
Confirm back prompt to exit app
<p>I'm currently working on an app that uses a lot the back button of android devices. I was wondering how to check if the activity is the last one and if the user presses back again, it doesn't exit the app except if the user presses back again, like with the 9gag app.</p> <p>Thank you!</p>
1
Create multiple instances of an object c#
<p>I'm trying to implement something to instantiate an object multiple times. The following code is to create an html listener and want them to be alive till the end of the process. So basically I don't want to write down 10 times rather find a way to automatically create it 10 times. </p> <p>I tried this but the listeners don't seem to be running.</p> <pre><code>public static void MultipleProxy() { var proxies = new List&lt;SocksWebProxy&gt;(); for (int i = 1; i &lt;= 10; i++) { proxies.Add(Proxy(i)); } } public static SocksWebProxy Proxy(int i) { var proxy = new SocksWebProxy(new ProxyConfig(IPAddress.Parse("127.0.0.1"), 7000 + i, IPAddress.Parse("127.0.0.1"), 9000 + i, ProxyConfig.SocksVersion.Five)); return proxy; } </code></pre>
1
How to search between two dates in C# with MS Access
<p>So for a group project I need to be able to search between two dates "Start_Date" &amp; "End_Date". Both of these fields use one Column from the database called "study_date". Currently I can only search for one date by entering the specified date into either field.</p> <p>Here is my code:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; namespace RRAS { public partial class formRRAS : Form { public OleDbConnection DataConnection = new OleDbConnection(); public formRRAS() { InitializeComponent(); } //When the form loads it sets the intial combo box RFR item to null private void formRRAS_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed. this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test); cmbRFR.SelectedItem = ""; } //AddRFR method, called in the NewRFRPopup public void AddRFR(object item) { cmbRFR.Items.Add(item); } //The code for the button that closes the application private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void btnSearch_Click(object sender, EventArgs e) { //This creates the String Publisher which grabs the information from the combo box on the form. //Select and Dataconnection are also defined here. string Department = String.IsNullOrEmpty(txtDepartment.Text)? "%" : txtDepartment.Text; string Start_Date = String.IsNullOrEmpty(txtStart.Text)? "%" : txtStart.Text; //DateTime start = DateTime.Parse(Start_Date); string End_Date = String.IsNullOrEmpty(txtEnd.Text)? "%" : txtEnd.Text; string Anatomy = String.IsNullOrEmpty(txtAnatomy.Text)? "%" : txtAnatomy.Text; string RFR = String.IsNullOrEmpty(cmbRFR.Text) ? "%" : cmbRFR.Text; string Comment = String.IsNullOrEmpty(txtComment.Text)? "%" : txtComment.Text; string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date LIKE'" + Start_Date + "'" + "AND study_date LIKE'" + End_Date + "'" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'"; //DataConnection connects to the database. string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb"; DataConnection = new OleDbConnection(connectiontring); //The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match. OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection); try { //It then clears the datagridview and loads the data that has been selected from the DataAdapter. database1DataSet.tblReject_test.Clear(); rdDataAdapter.Fill(this.database1DataSet.tblReject_test); } catch (OleDbException exc) { System.Windows.Forms.MessageBox.Show(exc.Message); } } //End of Search button //Temporary button thats loads the chart when clicked private void btnLoadChart_Click(object sender, EventArgs e) { { string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb"; DataConnection = new OleDbConnection(connectiontring); try { int count = database1DataSet.Tables["tblReject_test"].Rows.Count; DataConnection.Open(); OleDbCommand command = new OleDbCommand(); command.Connection = DataConnection; string query = "SELECT * FROM tblReject_test"; command.CommandText = query; OleDbDataReader reader = command.ExecuteReader(); while (reader.Read()) { charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count].ToString()); } DataConnection.Close(); } catch (Exception ex) { MessageBox.Show("Error " + ex); } } } //end of load chart button //This button loads the NewRFRPopup form private void addRFRToolStripMenuItem_Click(object sender, EventArgs e) { NewRFRPopup popup = new NewRFRPopup(this); popup.ShowDialog(); } } } </code></pre>
1
What is the purpose of col-lg-12 in Bootstrap?
<p>I saw a video where the author will just use</p> <pre><code>&lt;div class="col-lg-12"&gt; some content &lt;/div&gt; </code></pre> <p>inside of a <code>div.container</code> and a <code>div.row</code>. What is the purpose of that, if that is the only item in the row? I thought if you want something to occupy a whole row, you might just list it as <code>col-xs-12</code> so that it will affect all screen sizes. But if it is the only item, then won't it just automatically occupy all 12 columns? So why use that and why use <code>lg</code>?</p>
1
Remove leap year day from pandas dataframe
<p>I have the foll. dataframe:</p> <pre><code>datetime 2012-01-01 125.5010 2012-01-02 125.5010 2012-01-03 125.5010 2012-02-04 125.5010 2012-02-05 125.5010 2012-02-29 125.5010 2012-02-28 125.5010 2016-01-07 125.5010 2016-01-08 125.5010 2016-02-29 81.6237 </code></pre> <p>I would like to drop all rows corresponding to Feb 29th, resulting in foll. data frame:</p> <pre><code>datetime 2012-01-01 125.5010 2012-01-02 125.5010 2012-01-03 125.5010 2012-02-04 125.5010 2012-02-05 125.5010 2012-02-28 125.5010 2016-01-07 125.5010 2016-01-08 125.5010 </code></pre> <p>Right now, I am just doing it manually:</p> <p><code>df.drop(df.index[['2012-02-29']])</code>. How can I make it so that it works for all years, without haveing to manually specify row index.</p>
1
Format double number without thousand separator?
<p>Does anyone know the way to format a double value to a String without thousand separator (In Swift - ios).</p> <p>Note: I need to consider the current locale as some european languages use comma (,) as decimal separator. for example german languange write 12.50 as 12,50.</p> <p>So if the double value is 1250.25 </p> <pre><code>English-uk : 1250.25 German : 1250,25 </code></pre> <p>if I use following two ways (Whn english UK) I am getting the value as (1,212.50). BUT I want to format the value to String without thousant separator. So in this case 1212.50</p> <pre><code>var testOne = String.localizedStringWithFormat("%.2f", 1212.50) var testTwo = String(format: "%.2f", locale: NSLocale.currentLocale(), 1212.50) </code></pre>
1
Create a ListBox with items that expand when selected (Accordion)
<p>There's solutions to this problem for older XAML based UI frameworks (WPF/SL) but they're not easily adaptable to the Universal Windows Platform.</p> <p>I'm trying to create a list of items that show only limited details in default state and expands, when it's selected, to quickly edit some data.<br> I have not found a way to create a that expanding behavior, though it is similar to what the Windows 10 Mail app does, with conversations. When a message of a conversation is selected, the other messages of that conversation kind of drop down or slide down.</p> <p>Below is an example of a list where I'd like to display only the name at first.</p> <pre><code>&lt;ListBox ItemsSource="{x:Bind Persons}"&gt; &lt;ListBox.ItemContainerStyle&gt; &lt;Style TargetType="ListBoxItem"&gt; &lt;Setter Property="HorizontalContentAlignment" Value="Stretch" /&gt; &lt;/Style&gt; &lt;/ListBox.ItemContainerStyle&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate x:DataType="src:Person"&gt; &lt;StackPanel HorizontalAlignment="Stretch" Width="Auto"&gt; &lt;TextBlock Text="{x:Bind Path=Name, Mode=OneWay}" Margin="12, 15, 12, 0" FontSize="18.667" /&gt; &lt;TextBox HorizontalAlignment="Stretch" Margin="12, 12, 12, 0" FontSize="18.667" Text="{x:Bind Path=Name, Mode=TwoWay}" /&gt; &lt;TextBlock Text="Date of birth" Margin="12, 15, 12, 0" /&gt; &lt;DatePicker Margin="12, 5, 12, 0" Date="{x:Bind Path=DateOfBirth, Mode=TwoWay}" /&gt; &lt;TextBlock Text="Domicile" Margin="12, 15, 12, 0" /&gt; &lt;TextBox Margin="12, 5, 12, 0" Text="{x:Bind Path=Domicile, Mode=OneWay}" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>In WPF, such behavior could be achieved with triggers <code>Style.Triggers</code> but they're not available anymore.</p> <p>Original Source Code on <a href="https://github.com/elessar-ch/uwp-list-box-test/blob/master/ListBoxTest/MainPage.xaml" rel="noreferrer">GitHub</a></p>
1
HystrixCommand annotation - how to do fallback with throw
<p>I am using <a href="https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica" rel="nofollow">@HystrixCommand</a> to create fallbacks in a java server.</p> <p>Here is one method i have but the issue im having is im wondering am i allowed to throw in the fall back ?</p> <pre><code>@HystrixCommand(fallbackMethod = "doFallback", commandKey = "doFallbackCommand") public Response getGraphPoints(String Id, String position) { //do some work ... finally create a response return a_response; } public Response doFallback(String Id, String position) { //can i do this in hystrix command ? or do i really have to return a Response here?no other method will catch this throw for now throw new ServiceUnavailableException("points could not be found"); } </code></pre> <p>The Reason im asking is that when i run this im getting the following error:</p> <pre><code>ERROR [HystrixTimer-1] [com.netflix.hystrix.contrib.javanica.command.GenericCommand] [myserver] failed to processed fallback is the method: 'doFallback'. </code></pre>
1
Notice: Undefined property: WP_Error::$term_id
<p>Hello I am facing this problem .</p> <blockquote> <p>Notice: Undefined property: WP_Error::$term_id search.php on line 53</p> </blockquote> <p>And here is my code.</p> <pre><code>if($category_name != "All") { $thisCat = get_category(get_query_var('cat'),false); if(isset($thisCat)){ $catSearchID = $thisCat-&gt;term_id; } } else { $catSearchID = '-1'; } </code></pre> <p>Any body help please? Thanks</p>
1
How to feed shell script output to kafka?
<p>I am trying to feed some netflow data into kafka. I have some <code>netflow.pcap</code> files which I read like</p> <p><code>tcpdump -r netflow.pcap</code> and get such an output:</p> <pre><code>14:48:40.823468 IP abts-kk-static-242.4.166.122.airtelbroadband.in.35467 &gt; abts-kk-static-126.96.166.122.airtelbroadband.in.9500: UDP, length 1416 14:48:40.824216 IP abts-kk-static-242.4.166.122.airtelbroadband.in.35467 &gt; abts-kk-static-126.96.166.122.airtelbroadband.in.9500: UDP, length 1416 </code></pre> <p>. . . .</p> <p>In the official docs they mention the traditional way of starting a kafka producer, starting a kafka consumer and in the terminal input some data on producer which will be shown in the consumer. Good. Working.</p> <p>Here <a href="https://stackoverflow.com/a/33278191/2477978"> they show how to input a file to kafka producer</a>. Mind you, just one single file, not multiple files.</p> <p>Question is:</p> <p>How can I feed the output of a shell script into kakfa broker?</p> <p>For example, the shell script is:</p> <pre><code>#!/bin/bash FILES=/path/to/* for f in $FILES do tcpdump -r netflow.pcap done </code></pre> <p>I can't find any documentation or article where they mention how to do this. Any idea? Thanks!</p>
1
how to send email from a website hosted on s3
<p>I have a website hosted on S3 on amazon web services. I want to receive emails on my gmail account from the visitors of my website if they wish to contact me. I'm confused with the steps for the setup as I tried working around with SES on amazon web service but am completely off tracK I believe.</p> <p>Thanks.</p>
1
Which design pattern to use to process different files in java?
<p>I have simple task to read the information from different files <strong>xml, rdf, txt</strong> with different structure and put it in some <strong>POJO</strong> custom object(MyObject). SO I am wondering which design pattern to use to make my code with better design.</p> <p>I think on the problem and I think I need <em><a href="http://www.tutorialspoint.com/design_pattern/factory_pattern.htm" rel="nofollow">Factory Patter</a></em> and the <em><a href="http://www.tutorialspoint.com/design_pattern/iterator_pattern.htm" rel="nofollow">Iterator Pattern</a></em>. On the factory to pass the file:</p> <pre><code>ReaderFactory factory = new ReaderFactory("input.rdf"); //ReaderFactory factory = new ReaderFactory("input.xml"); Iterator&lt;MyObject&gt; iter = factory.getIterator(); </code></pre> <p>So the factory base on the file extension to choose which implemnetation of the iterator to return - these which reads rdf,xml or txt. Then with this iterator I easily can process the objects. Add add new files extensions reading in the future.</p>
1
Submitting spark app as a yarn job from Eclipse and Spark Context
<p>I can already submit <code>local</code> spark jobs (written in Scala) from my Eclipse IDE. However, I would like to modify my Spark context (inside my application) so that when I 'Run' the app (inside Eclipse), the job will be sent to my remote cluster using Yarn as a resource manager. </p> <p>Using <code>spark-submit</code>, I can successfully submit the job to the cluster as: <code>spark-submit --class &lt;main class&gt; --master yarn-cluster &lt;jar&gt;</code></p> <p>I want to achieve the same result inside the IDE. My sbt config (app root directory) looks like: <code> libraryDependencies += "org.apache.spark" %% "spark-core" % "1.5.1" libraryDependencies += "org.apache.spark" %% "spark-yarn" % "1.5.1" % "provided" </code> Inside my app: <code> val conf = new SparkConf().setAppName("xxx").setMaster("yarn-cluster") </code> However, I am getting the following errors:</p> <p><code> Detected yarn-cluster mode, but isn't running on a cluster. Deployment to YARN is not supported directly by SparkContext. Please use spark-submit. </code></p>
1
Bootstrap Sticky navbar is causing vertical scrolling in collapsed mode
<p>I am building a <code>navbar</code> that is supposed to stick to the top of the page. I used <code>.navbar-fixed-top</code> class to accomplish that and gave the body element, a padding of <code>70px</code>. Now in the collapsed mode (mobile resolution), when toggled, it gives a vertical navigation. </p> <p>Not sure where this scrolling is coming from.</p> <p><strong>Here's the code:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header class=" container-fluid navbar-fixed-top"&gt; &lt;!-- header navbar --&gt; &lt;nav class="navbar navbar-default"&gt; &lt;div class="container"&gt; &lt;!-- Brand and toggle get grouped for better mobile display --&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="market.html"&gt;&lt;img src="images/logo-inner.jpg" / alt="B-Hive: Expand your business"&gt;&lt;/a&gt; &lt;/div&gt; &lt;!-- Collect the nav links, forms, and other content for toggling --&gt; &lt;div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"&gt; &lt;!-- Form search start --&gt; &lt;form class="navbar-form navbar-left" role="search" class="top-search-padding"&gt; &lt;div class="form-group"&gt; &lt;div class="search-div ui-widget"&gt; &lt;input id="tags" type="text" class="txt-search" placeholder="Search people, products and services"&gt; &lt;button type="submit" class="btn-search"&gt;&lt;img src="images/search-icon.png" /&gt;&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;!-- Form search end --&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li class="top-menu-links-active"&gt;&lt;a href="#"&gt;MARKET&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="top-menu-links" href="#"&gt;EXHIBITIONS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="top-menu-links" href="#"&gt;MESSAGES&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="top-menu-links" href="#"&gt;DASHBOARD&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="top-menu-links" href="#"&gt;CART&lt;/a&gt;&lt;/li&gt; &lt;li class="profile-pic-padding"&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle custom-dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"&gt;&lt;img class="" src="images/profile-pic.fw.png" /&gt; &lt;span class="caret"&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Account&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Privacy&lt;/a&gt;&lt;/li&gt; &lt;li role="separator" class="divider"&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Switch Accounts&lt;/a&gt;&lt;/li&gt; &lt;li role="separator" class="divider"&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Language &lt;span class="caret"&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;EN&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;ΨΉ&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!-- /.navbar-collapse --&gt; &lt;/div&gt; &lt;!-- /.container-fluid --&gt; &lt;/nav&gt; &lt;!-- /header navbar --&gt; &lt;/header&gt;</code></pre> </div> </div> </p>
1
SQL time and date formatting against dual table
<p>I am trying to only display the date and time of a table in a certain format. This format is DD-MON-YYYY and the time HH24:MI:SS. I don't understand how to make both formats work together. I can get them to function separately.</p> <pre><code>select to_char(sysdate, 'DD-MON-YYYY', systimestamp,'HH24:MI:SS') from dual; </code></pre> <p>My error is 'too many arguments'. I want to understand why it isn't working.</p>
1
UMDF, cannot specify [ClassInstall32] section for Microsoft-defined class
<p>I'm working with the next tutorial: <a href="https://msdn.microsoft.com/en-us/library/windows/hardware/hh706184(v=vs.85).aspx" rel="nofollow noreferrer">How to write your first USB client driver</a>.</p> <p>And I've got a problem with compiling a project, I've got the next error:</p> <p><a href="https://i.stack.imgur.com/MwYJi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MwYJi.png" alt="enter image description here"></a></p> <p>I was trying to do the steps closely to the description in tutorial, but always got the error above, when compiling the project.</p> <p>Also, I've tried to search, but didn't find any useful information.</p> <p>Possible additional info, which might help you to give me a piece of advice:</p> <ul> <li>INF-file: <a href="http://pastebin.com/71d6bbQm" rel="nofollow noreferrer">http://pastebin.com/71d6bbQm</a></li> <li>Using Windows 10, latest WDK and VS2015</li> <li>Have started exactly <code>USB User-Mode Driver</code> template as was mentioned in tutorial</li> </ul>
1
PHP counting MYSQL rows that contain the same value in many columns
<p>Here is the content of my table: <a href="https://i.stack.imgur.com/0ZGWf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0ZGWf.jpg" alt="enter image description here"></a></p> <p>How to count all names in different table cells to get a result like this?</p> <blockquote> <ul> <li>Bob-7</li> <li>Alex-3</li> <li>Ivan-5</li> <li>Nina-5<br> .........</li> </ul> </blockquote> <p>With this code:</p> <pre><code>&lt;?php $q= mysqli_query($db, 'SELECT * FROM names'); while ($all = mysqli_fetch_array($q)) { $k1= $all['Name1']; $k2= $all['Name2']; $k3= $all['Name3']; $k4= $all['Name4']; $k5= $all['Name5']; $k6= $all['Name6']; $arr[]= $k1; $total_values = array_count_values($arr); } foreach ($total_values as $key =&gt; $value) { echo $key .'-'. $value .'&lt;br&gt;'; } </code></pre> <p>My output result is:</p> <blockquote> <ul> <li>Bob-3</li> <li>Alex-1</li> <li>Ivan-1</li> <li>Nina-2</li> </ul> </blockquote> <p>When I change my code to:</p> <pre><code>&lt;?php $q= mysqli_query($db, 'SELECT * FROM names'); while ($all = mysqli_fetch_array($q)) { $k1= $all['Name1']; $k2= $all['Name2']; $k3= $all['Name3']; $k4= $all['Name4']; $k5= $all['Name5']; $k6= $all['Name6']; $arr=array($k1, $k2); $total_values = array_count_values($arr); foreach ($total_values as $key =&gt; $value) { echo $key .'-'. $value .'&lt;br&gt;'; } } </code></pre> <p>My output result is:</p> <blockquote> <ul> <li>Bob-1</li> <li>Alex-1</li> <li>Ivan-1</li> <li>Nina-1</li> <li>Nina-1</li> <li>Bob-1</li> <li>Bob-1</li> <li>Ivan-1</li> <li>Nina-1</li> <li>Nina-1<br> .......</li> </ul> </blockquote> <p>What is wrong and what I have to do to add $k2, $k3....$k6 in the array $arr?</p>
1
Could not cast value of type 'nsnull' to 'nsstring'
<p>I'm trying to retrieve images from firebase when I start the simulated it crash and I get this message " <strong>Could not cast value of type 'NSNull' (0x10eaf2378) to 'NSString' (0x10eee2b20).</strong> " this is my code</p> <p>class ViewController: UIViewController {</p> <pre><code>@IBOutlet weak var gameName: UILabel! @IBOutlet weak var videoImage: UIImageView! @IBOutlet weak var uploadImage: UIButton! var ref = Firebase(url:"https://xxx.firebaseio.com/images/") var imageRef = Firebase(url:"https://xxx.firebaseio.com/images/image/string") var base64String: NSString! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. imageRef.observeEventType(.Value, withBlock: { (snapshot) -&gt; Void in self.base64String = snapshot.value as? String let decodeData = NSData(base64EncodedString: snapshot.value as! String, options: NSDataBase64DecodingOptions()) let decodeImage = UIImage(data: decodeData!) self.videoImage.image = decodeImage print(self.base64String) }) { (error) -&gt; Void in print(error.description) } } </code></pre>
1
Guzzle 6 Basic Authentication continue with Session Cookie not working
<p>With Curl i authenticate to the server, get the session cookie written to file (cookies) and use it on the next request.</p> <p><code>curl --basic --digest --user restuser:restpassword --cookie-jar cookies --insecure https://xxx.example.dom/api/authentication</code></p> <p>Copy session_id cookie value from cookies file and use it:</p> <p><code>curl --cookie session_id=910f5e79aaf44dd8dc3c26e79e6d08bb22a86674 --insecure https://xxx.example.dom/api/configuration</code></p> <p>I wanted to implement this with Guzzle 6.1.1. It passes the basic authentication get the session cookie but do not pass it to the next request.</p> <pre><code>use GuzzleHttp\Client; use GuzzleHttp\Cookie\SessionCookieJar; $jar = new \GuzzleHttp\Cookie\SessionCookieJar('session_id', true); $client = new GuzzleHttp\Client([ 'base_uri' =&gt; REST_URL, 'cookies' =&gt; $jar, 'debug' =&gt; true ]); // authenticate $res = $client-&gt;request('GET', 'authentication', [ 'verify' =&gt; false, 'auth' =&gt; [REST_USER, REST_PASS] ]); // send authenticated request $res = $client-&gt;request('GET', 'configuration', [ 'verify' =&gt; false ]); </code></pre> <p>In my understanding from the documentation, by setting persistent session cookies and using it while creating client, Guzzle should send them automagically within the next request am i wrong?</p> <p>Thanks.</p> <p>Note: Here is the debug output.</p> <pre><code>HTTP/1.1 200 OK X-Frame-Options: SAMEORIGIN Content-Length: 129 Content-Language: en Server: REST Allow: DELETE, GET, HEAD, POST, PUT Date: Sun, 07 Feb 2016 03:53:02 GMT Content-Type: application/json Set-Cookie: session_id=488df4282feb714f3fd2e36a1bb02ea06f923eb8; expires=Sun, 07 Feb 2016 04:13:02 GMT; httponly; Path=/; secure * Connection #0 to host xxx.example.dom left intact 200Array{ "_meta": { "href": "/api/authentication", "next": "/api", "transaction": "/api/transaction" } } * Found bundle for host xxx.example.dom: 0x100c18510 * Re-using existing connection! (#0) with host xxx.example.dom * Connected to xxx.example.dom (192.168.68.100) port 443 (#0) &gt; GET /api/configuration HTTP/1.1 User-Agent: GuzzleHttp/6.1.1 curl/7.41.0 PHP/5.6.7 Host: xxx.example.dom HTTP/1.1 401 Unauthorized X-Frame-Options: SAMEORIGIN Content-Length: 284 Content-Language: en Server: REST Allow: DELETE, GET, HEAD, POST, PUT Date: Sun, 07 Feb 2016 03:53:02 GMT Content-Type: application/json Set-Cookie: session_id=d1c231b1a093a1d9a9041597b3d708d32203e3f0; expires=Sun, 07 Feb 2016 04:13:02 GMT; httponly; Path=/; secure * Connection #0 to host xxx.example.dom left intact &lt;b&gt;Fatal error&lt;/b&gt;: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: `GET https://xxx.example.dom/api/configuration` resulted in a `401 Unauthorized` response: </code></pre>
1
How tar xvfz works in cygwin?
<p>I tried tar with xvfz and -xvfc both didn't work in Cygwin on Windows.</p> <pre><code>$ tar xvfz sshpass-1.0.5.tar.gz tar (child): sshpass-1.0.5.tar.gz: Cannot open: No such file or directory tar (child): Error is not recoverable: exiting now tar: Child returned status 2 tar: Error is not recoverable: exiting now </code></pre> <p>Here cmd tar with '-'</p> <pre><code>$ tar -xvfz sshpass-1.0.5.tar.gz tar: z: Cannot open: No such file or directory tar: Error is not recoverable: exiting now </code></pre> <p>Question : 1 . How does tar works with <code>-</code> or without <code>_</code> ?</p> <p>Please suggest to execute tar -xvfz sshpass-1.0.5.tar.gz.</p>
1
Dynamically creating Radio Buttons and Assigning selected Values PHP
<p>Hi I am pretty new to PHP. I am trying to get the selected value from my radio button in PHP but I am unable to get the selected value. I have populated the values by connecting to my DB (MySQL) but I am unable to get the assigned value from the radio button. It always escapes the if condition and says "No Value Selected" and I am not able to assign the value and save it to my DB</p> <p>Appreciate your help. </p> <p>My index.php is as follows `</p> <pre><code>&lt;?php session_start(); $_SESSION['timein']= time(); ?&gt; &lt;?php include("config.php"); $conn = mysqli_connect($dbHost, $dbuser, $dbpassword, $dbDatabase); $query_salutation_type='SELECT salutation_description FROM tbl_salutation;'; $select_salutation_type=mysqli_query($conn, $query_salutation_type); while($row1 = mysqli_fetch_array($select_salutation_type)) { echo '&lt;input type="radio" name="salutation_description" value="'.$row1[0].'"/&gt;'.$row1[0]; } ?&gt; &lt;html&gt; &lt;body&gt; &lt;form method="post" action="capture_data.php" &gt; &lt;input type="submit" name="submit" value="Submit"/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>`</p> <p>My capture_data.php is as follows</p> <pre><code> &lt;?php if(isset($_POST['submit'])) { if(isset($_POST['salutation_description'])) { $selected_val = $_POST['salutation_description']; echo "You have selected :" .$selected_val; } else { echo 'No Value Selected'; } } ?&gt; </code></pre> <p><a href="https://i.stack.imgur.com/i8iWr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i8iWr.jpg" alt="index.php"></a></p>
1
Excel - Conditional row from an array to COUNTIF from VLOOKUP
<p>I don't know if I'm going about this the wrong way but it seems like it should be simple. Column A has a list of Names. Along each row is several "W"'s. Another separate field has a drop down representing Column A names. I want to count the number of "W"'s in a row corresponding to what name I select. I've tried using VLOOKUP and COUNTIF but I can't figure out how to select the entire array and then single out the one row that matches my selected name. I can get it working with a bunch of IF statements but thats far too time consuming as I'm manually matching the name to the row (and it isn't future proof).</p>
1
Plotly Draw line according to an equation
<p>I would like to drow a line according to an equation, for example: y=2x+3.</p> <p>Is there any way to do this in plotly javascript (or python) without having to sample the equation at different points?</p>
1
ExtJS 6.0.1 disable cell selection
<p>I'm trying to disable the cell selection in my Ext.grid.Panel. I found out there are few selectionTypes and selectionModes, but neither worked for me. Would be great if I could achieve this by using the framework.</p> <p>Thanks in advance.</p> <p>Update to my question: I want to select a row, but not a single column. Is it possible to disable the cell selection, but allow the user to select the row?</p> <hr> <h2>Update</h2> <p>I found a better solution than the suggested ones:</p> <p>Just use the <a href="https://docs.sencha.com/extjs/6.0.1/classic/Ext.view.Table.html#css_var-S-$grid-row-cell-focus-border-width" rel="nofollow noreferrer">theme-variable of the component</a>. By setting the value to 0px, the selection disappears completely.</p>
1
Advanced search REST API
<p>My requirement is to implement advanced search Rest API for searching the phones. The URI for the search API is <a href="http://myservice/api/v1/phones/search?q=" rel="noreferrer">http://myservice/api/v1/phones/search?q=</a>${query_expression}</p> <p>Where <em>q</em> is the complex query expression. Have the following questions </p> <p>1) Since advanced search involves a lengthy query expression, the URI will not fit in a GET call. Is it alright to implement the search API via POST request and still maintain the RESTfulness?</p> <p>2) I have come across the following implementations for the advanced search:</p> <ul> <li>1st approach - Send the complete infix expression for the query expression. eg.</li> </ul> <p><code>PHONENAME STARTSWITH 'AR' AND ( PHONETYPE = '4G' OR PHONECOLOR = 'RED')</code></p> <ul> <li><p>2nd approach - Constructing entire query expression in the form of a json. eg. </p> <p><code>{"criteria":[ {"index":1,"field":"PHONENAME","value":"AR","comparator":"STARTSWITH"}, {"index":2,"field":"PHONETYPE","value":"4G","comparator":"EQUALS"}, {"index":3,"field":"PHONECOLOR","value":"RED","comparator":"EQUALS"} ],"criteria":"( 1 AND (2 OR 3) )"}</code></p></li> <li><p>3rd approach - Alternative way to implement the query expression as a json. eg.</p> <p><code>{"and":[ {"field":"PHONENAME","value":"AR","comparator":"STARTSWITH"}, "or":[ {"field":"PHONETYPE","value":"4G","comparator":"EQUALS"}, {"field":"PHONECOLOR","value":"RED","comparator":"EQUALS"}] ]}</code></p></li> </ul> <p>Which approach would be considered more RESTful out of the three? Suggestions for any other approaches are welcome :)</p>
1
Testing SOAP Web Services in Java
<p>I am just wondering, is there any Java library to test SOAP web services?</p> <p>Here is my requirement. There is already an existing web service. The web service can be used to create a record in the database by sending number of input parameters along with authentication in the SOAP header. Now I want to test this web service with different combinations of data and assert the data in the database.</p> <p>It will be handy if there is an API such that I can create my own automated test suite in Java by interacting with that API. I can handle the response and assert the data in database using JDBC and I also need to verify it on the UI Screen using Selenium.</p> <p>I came across several APIs in this page: <a href="http://java-source.net/open-source/web-services-tools" rel="nofollow">http://java-source.net/open-source/web-services-tools</a></p> <p>I am not sure whether I can use API Apache Axis2 in my situation or not.</p> <p>I know we can use SOAP UI but there is not much documentation. <a href="https://www.soapui.org/developers-corner/integrating-with-soapui.html" rel="nofollow">https://www.soapui.org/developers-corner/integrating-with-soapui.html</a></p> <p>Any thoughts on this?</p> <p>Thanks.</p>
1
Is it possible to view a PDF file from an URL link using Quick Look Framework
<p>As the title says, I need to display a PDF file stored in a remote server without downloading it on the device just by using an URL link. Is it possible to do it by using the <code>Quick Look</code> framework?</p> <p>I am using this code below:</p> <pre><code>- (void)openDocument { QLPreviewController *docPreviewController = [[QLPreviewController alloc] init]; [docPreviewController setDataSource:self]; [docPreviewController setDelegate:self]; [docPreviewController setCurrentPreviewItemIndex:sender.tag]; [self.destinationViewController presentViewController:docPreviewController animated:true completion:nil]; } - (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller { return 1; } - (id&lt;QLPreviewItem&gt;)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index { return [NSURL fileURLWithPath:@"http://www.domain.com/file.pdf"]; } </code></pre> <p>But I have this problem in the console:</p> <pre><code>UIDocumentInteractionController: invalid scheme https. Only the file scheme is supported. </code></pre>
1
How to leave a div and an image over a carousel?
<p>I want to make a carousel and over it, a div and then to give that effect to be superimposed. Try to make as this <a href="https://jsfiddle.net/gtw7375/jdbzqyaL/" rel="nofollow noreferrer">EXAMPLE</a>, but without success. When I add such properties (<code>absolute and relative</code>) the code of the carousel it does not.</p> <p><a href="https://i.stack.imgur.com/sPNEF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sPNEF.png" alt="enter image description here"></a></p> <p>My DIV Overlay => <code>id="faixa"</code></p> <p>The slide in background shaped carousel. The green div and logo superimposed on the carousel.</p> <p>I tried something like:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#myCarousel{ position: absolute; } #fixa{ position: absolute; width: 20%; height: 400px; background: black; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;div id="myCarousel" class="carousel slide" data-ride="carousel"&gt; &lt;ol class="carousel-indicators"&gt; &lt;li data-target="#myCarousel" data-slide-to="0" class="active"&gt;&lt;/li&gt; &lt;li data-target="#myCarousel" data-slide-to="1"&gt;&lt;/li&gt; &lt;/ol&gt; &lt;div class="carousel-inner" role="listbox"&gt; &lt;div id="fixa"&gt; DIV QUE SERÁ SOBREPOSTA &lt;/div&gt; &lt;div class="item active"&gt; &lt;img src="http://s3.amazonaws.savoir.com.br/cea.com.br/imagem/cadastrocqlv/imagem/cadastrocqlv-53440.jpg"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src="http://www.asia-turismo.com/imagens/asia-imagem.jpg"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>How to make this?</p>
1
Error: "Can't find keyplane that supports type 4 for keyboard"
<p>on this line of code: </p> <pre><code>if diceRoll == userGuessTextField.text { </code></pre> <p>I get this error:</p> <pre><code>2016-02-04 18:38:34.756 How Many Fingers[2972:158461] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 1336863583_PortraitChoco_iPhone-Simple-Pad_Default fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) </code></pre> <p>Here is my code:</p> <pre><code>import UIKit class ViewController: UIViewController { @IBOutlet var userGuessTextField: UITextField! @IBOutlet var resultLabel: UILabel! @IBAction func guess(sender: AnyObject) { let diceRoll = String(arc4random_uniform(6)) if diceRoll == userGuessTextField.text { resultLabel.text = "You're right!" } else { resultLabel.text = "Wrong! It was a " + diceRoll } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } </code></pre> <p><a href="https://i.stack.imgur.com/Y8slL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y8slL.png" alt="enter image description here"></a></p>
1
I'm not getting the Welcome screen showing before my Android Studio opens
<p>I just installed my Android Studio but at first I had a couple of problems getting it started due to having linked it to the wrong path, though I eventually managed to get the correct path linking to my SDk. I don't necessarily have any problem starting my Android IDE, however it doesn't start as usual with the weclome screen where I can just easily access "new Project" and co. Is this just fine and should I not look after fixing that and just start my project from the main software or should I look to get my Welcome page showing, and if so how could I do that?</p>
1
How to take input as String given the String Length
<p>How to take input from User as String given the String Length</p> <p>The problem link:</p> <p><a href="http://www.practice.geeksforgeeks.org/problem-page.php?pid=295" rel="nofollow">http://www.practice.geeksforgeeks.org/problem-page.php?pid=295</a></p> <p>MyApproach:</p> <p>I used Scanner for the task to take the number of testcases and then took the String length as input:</p> <p>But I am confused how to take String of specified length.My search found that there is no method or constructor which can take string of specified length.</p> <p>Can Anyone guide?</p> <p>Below is my code:</p> <pre><code> Scanner sc=new Scanner(System.in); int T=sc.nextInt(); for(int i=1;i&lt;=T;i++) { int Strlength=sc.nextInt(); String strnew=sc.next(); //How to take Stringofspecified character .......... ......... } </code></pre>
1
Show/Hide Rows Per Dropdown Selection
<p>I found code online as an example that I have tweaked to show or hide specific rows depending on the selection I choose within a dropdown in my Excel file. </p> <p>The macro is not working no matter what I try.</p> <p>My code is as follows (also attached screenshot of rows under question 2 (2a - 2d) that are not showing/hiding) <a href="https://i.stack.imgur.com/RSvYf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RSvYf.jpg" alt="Screenshot of Excel Doc"></a></p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = "$F$13" Then If Range("F13").Value = "Yes" Then Rows("14:17").EntireRow.Hidden = False End If If Range("F13").Value = "No" Then Rows("14:17").EntireRow.Hidden = True End If If Range("F13").Value = " " Then Rows("14:17").EntireRow.Hidden = True End If End Sub </code></pre>
1
How to return data using cURL call
<p>This returns a token, like: {"token":"260e5b8adf74af6be5dfa250c5ad93c8"}</p> <p>And I want just want the content part: 260e... Which I think I can get it by using $getInfo['token'], right?</p> <pre><code>$user="admin"; $password="Moodle15!"; $services="moodle_mobile_app"; $url = "https://localhost/moodle/login/token.php?username=".$user."&amp;password=".$password."&amp;service=".$services.""; $ch = curl_init($url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURL_RETURNTRANSFER, true); $getURL = curl_exec($ch); $getInfo = json_decode($getURL, true); $displayToken = $getInfo['token']; echo $displayToken; curl_close($ch); </code></pre> <p>And I don't know what's going on with the CURL_RETURNTRANSFER.</p> <p>And the error:</p> <pre><code>Notice: Use of undefined constant CURL_RETURNTRANSFER - assumed 'CURL_RETURNTRANSFER' in C:\xampp\htdocs\moodle\cURL_script.php on line 12 Warning: curl_setopt() expects parameter 2 to be long, string given in C:\xampp\htdocs\moodle\cURL_script.php on line 12 {"token":"260e5b8adf74af6be5dfa250c5ad93c8"} </code></pre> <p>EDITED: </p> <p>And if I had:</p> <pre><code>{"id":4,"username":"Jhon","firstname":"smith","lastname":"Reches","fullname":"Jhon smith","email":"[email protected]","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/25\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/25\/user\/icon\/f1","groups":[],"roles":[{"roleid":5,"name":"","shortname":"student","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"},{"id":2,"fullname":"Grup de Recerca","shortname":"Grp. Recerca"}]} </code></pre> <p>How can I acces to 'username'? or 'fullname' when you know there are many 'fullname' in it?</p> <p>EDITED2:</p> <p>New code I have now:</p> <pre><code>$token = "260e5b8adf74af6be5dfa250c5ad93c8"; $funcion="core_enrol_get_enrolled_users"; $courseid="3"; $format="json"; $url= "https://localhost/moodle/webservice/rest/server.php?wstoken=".$token."&amp;wsfunction=".$funcion."&amp;courseid=".$courseid."&amp;moodlewsrestformat=".$format.""; $ch = curl_init($url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $getURL = curl_exec($ch); $getInfo = json_decode($getURL, true); $email = $getInfo[2]['email']; echo $email."&lt;/br&gt;"; curl_close($ch); </code></pre> <p>Now $email contains [email protected] but I have many results, how can I manage to display all of them with a foreach? Because it is a multidimentional array. See below.</p> <pre><code>[{"id":4,"username":"jhon1.smith1","firstname":"Jhon1","lastname":"Smith1","fullname":"jhon1 smith1","email":"[email protected]","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/25\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/25\/user\/icon\/f1","groups":[],"roles":[{"roleid":5,"name":"","shortname":"student","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"},{"id":2,"fullname":"Grup de Recerca","shortname":"Grp. Recerca"}]},{"id":5,"username":"jhon1.smith1","firstname":"Josep","lastname":"jhon1 ","fullname":"jhon1 smith1","email":"[email protected]","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/26\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/26\/user\/icon\/f1","groups":[],"roles":[{"roleid":5,"name":"","shortname":"student","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"},{"id":2,"fullname":"Grup de Recerca","shortname":"Grp. Recerca"}]},{"id":6,"username":"jhon1.smith1","firstname":"jhon1","lastname":"smith1","fullname":"jhon1 smith1","email":"[email protected]","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/32\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/32\/user\/icon\/f1","groups":[],"roles":[{"roleid":1,"name":"","shortname":"manager","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"},{"id":2,"fullname":"Grup de Recerca","shortname":"Grp. Recerca"}]},{"id":7,"username":"jhon1.jhon1","firstname":"jhon1","lastname":"jhon1","fullname":"jhon1 smith1","email":"[email protected]","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/35\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/35\/user\/icon\/f1","groups":[],"roles":[{"roleid":5,"name":"","shortname":"student","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"}]},{"id":8,"username":"jhon1.smith1","firstname":"jhon","lastname":"smith1","fullname":"jhon1 smith1","email":"[email protected]","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/41\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/41\/user\/icon\/f1","groups":[],"roles":[{"roleid":3,"name":"","shortname":"editingteacher","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"}]}] </code></pre> <p>and I wish:</p> <pre><code>[email protected] [email protected] foo2@.. </code></pre>
1
doctrine dql/queryBuilder with a foreach or array in parameters
<p>In my symfony aplication, I recover a variable as a string by my ajax script.</p> <p>This variable looks like this:</p> <pre><code>$slug = "1-2-3-4-4-5-6-7" /* it could more*/ $vars = explode('-',$slug ); /*push the $slug string in an array */ /* recover all value of the array */ foreach ($vars as $var) { echo $var; } </code></pre> <p>Now I need to use this foreach in a <code>dql</code> or a <code>query builder</code> because all $var are ids of an entity and i need to pass all this value to get the right result.</p> <p>How can I make a query with an array of parameter or make a foreach in doctrine query builder ?</p> <p>I have already try something this in a queryBuilder method:</p> <pre><code>-&gt;setParameters("id" =&gt; $vars); </code></pre> <p>it returns me an error : <code>SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)</code></p> <p>I try this too in the queryBuilder:</p> <pre><code>-&gt;setParameters(array('id' =&gt; array($vars))); </code></pre> <p>Here I have no error, but it does not return the good result. Indeed I have <strong>only one</strong> result in database if there are many ids.</p>
1
Why is tail not working here?
<p>My csh script</p> <pre><code>#!/bin/csh # C-schell script to increase the boundingbox.... echo '%\!PS-Adobe-3.0 EPSF-3.0' echo '%%BoundingBox: 0 0 1100 1100' tail +3 $argv[1] </code></pre> <p>Called here</p> <pre><code>csh bbox.csh plt &gt;! plt_P1.ps </code></pre> <p>But I have</p> <pre><code>csh -f bbox.csh plt tail: cannot open β€˜+3’ for reading: No such file or directory </code></pre> <p>What is <code>tail</code> supposed to do?The guy who wrote the code uses Darwin,I am on Ubuntu 14.04.</p>
1
remove document objectid only in populated array in mongoose
<p>I'm having a really difficult time trying to remove the objectids from an array using a populated query.</p> <p>this is my Schema</p> <pre><code>var userSchema = new Schema({ username: String, password: String, books: [{type: Schema.Types.ObjectId, ref: 'Book'}] } ); var bookSchema = new Schema({ bookid: {type:String, unique:true, required:true}, imgURL: String, fortrade: Boolean }); </code></pre> <p>The problem is with the query shown below. it removes removes the book schema item when I only want it to remove the objectid in the books array.</p> <pre><code>users.findOne({'_id':userid}).populate('books').exec(function(usererr,userdata){ if (usererr) return console.error(usererr); userdata.books.forEach(function(elm,idx){ if(elm.bookid==_book.bookid){ userdata.books[idx].remove(); } }) }); </code></pre>
1
how to set pom.xml to run main class in maven project in netbeans
<p>May I ask what I should do to run main class in a maven project created in Netbeans IDE? I set the pom.xml like the following, but it doesn't work.Is there any other configuration in Netbeans I should modify?</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.mycompany&lt;/groupId&gt; &lt;artifactId&gt;mavenproject2&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;mavenproject2&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;build&gt; &lt;plugins&gt; &lt;!-- &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;2.3.2&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; --&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.2.1&lt;/version&gt; &lt;configuration&gt; &lt;mainClass&gt;com.mycompany.mavenproject2.App&lt;/mainClass&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.10&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;/properties&gt; &lt;/project&gt; </code></pre>
1
PHP url into html img src
<p>i'm using and url from Facebook to insert into HTML img src .. that url is not an image, this url (when opened on a browser) redirects to an image.</p> <pre><code> &lt;img src="https://graph.facebook.com/274084006029120/picture?width=100" /&gt; </code></pre> <p>This image is shown correctly everywhere.</p> <p>Then I build a cover.php program that only redirect to an <a href="http://../image.jpg" rel="nofollow">http://../image.jpg</a></p> <p>Then i add on HTML source</p> <pre><code> &lt;img src="https://.../cover.php" /&gt; </code></pre> <p>On most browsers and emails this cover.php program Works fine and shows the picture. But on some components (editors) seems the php is not executed and the picture is not show.</p> <p>How can i solve this ? or how can i do redirect (need some code before) to work like Facebook redirect ?</p> <p>Thanks a lot !</p>
1
How to make a continuous listener in javascript?
<p>I am learning so perhaps my question could be rephrased or re-worded.</p> <ol> <li>When I click div=> variable= variable+1;</li> <li>What I want is when 'variable===3', it console.log('I am 3).</li> </ol> <p>My script is not doing what I am trying to do, but this is my try.</p> <pre><code>&lt;script type="text/javascript"&gt; element = document.getElementById("id"); variable=0; function loading(){ element.addEventListener("click",function(){ variable=variable+1; console.log(variable); }); }; function check(){ if(variable===3){console.log('I am 3');}; }; loading(); check(); &lt;/script&gt; </code></pre> <p>Should I call check() each time object is clicked? Or should I create a listener to call check() every time 'variable' is changing? Or another solutions?</p>
1
Application insights returns 400 error
<p>Today I found an issue with application insights. Now it returns me 400 error when I try to track event:</p> <p>POST <a href="https://dc.services.visualstudio.com/v2/track" rel="nofollow">https://dc.services.visualstudio.com/v2/track</a> 400 (106: Field 'type' on type 'Device' is of incorrect type. Expected: string, Actual: undefined)</p> <p>Nothing was changed that can lead to this issues. If I event try to provide it with type field it just cause an other error (type for User).</p> <p>I'm using app insights via angularJs <a href="https://github.com/khaines/angular-applicationinsights" rel="nofollow">module</a>.</p> <p>Can anybody help me?</p> <p>Thanks!</p>
1
npm link "The file is marked as an executable but could not be run by the operating system."
<p>So I made a cli with <code>package.json</code> that specifies a bin file.</p> <p>I <code>npm link</code>'d it. Then I created a new folder on my desktop and <code>npm link foocli</code> which installed it fine to that directory's <code>node_modules</code> folder.</p> <p>Then I try to run the cli from that dir and it throws:</p> <p><code>The file '/usr/local/bin/foocli' is marked as an executable but could not be run by the operating system.</code></p> <p>Any idea what's causing this and how I can fix it?</p>
1
Most efficient way to sum a list in Python
<p>Among the ways to obtain the sum of a list <code>A</code> of ints in Python are the following two:</p> <ol> <li><p>Built-in <code>sum</code> function: <code>sum(A)</code></p></li> <li><p>Reduce function with adder lambda: <code>reduce(lambda x, y: x + y, A)</code></p></li> </ol> <p>Is there any speed advantage to using either of these, or are their performances roughly the same?</p>
1
Need to make my texfield output bold, italic and both when the JCheckButtons are selected
<p>I have created a basic GUI which has 2 JCheckButtons (bold, italic) and 3JRadioButtons in a button group of font styles (times, helvetica, courier). There is also a textfield which will display a string of the font style, such as times, in that style, and if the bold or italic buttons are pressed then the text will also be bold or italic (or both). So far I have managed to add action listeners which copy the font name from the radio buttons to the textfield but I am having trouble making this text be in the associated font style. I also am having trouble with the functions of my bold and italic buttons. </p> <p>Here is the code for my GUI layout (the layout is how I want it to be, only problem is with the functionality of my buttons:</p> <pre><code>package weekTwo; import javax.swing.*; import java.awt.*; import java.awt.GridBagConstraints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class taskTwo { public static void main(String[] args) { JFrame window = new JFrame("Font Chooser"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setSize(500, 100); FontSetter fontSetter = new FontSetter(); Container pane = window.getContentPane(); pane.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); JTextField text = new JTextField(); gbc.gridx = 2; gbc.gridy = 2; gbc.weightx = 1; gbc.weighty = 1; gbc.insets = new Insets(0, 0, 5, 5); //padding constraints gbc.fill = GridBagConstraints.BOTH; //text field fills cell pane.add(text, gbc); JCheckBox bold = new JCheckBox("Bold"); gbc.gridx = 0; //sets x position to 0 gbc.gridy = 1; bold.addActionListener(new Bold(fontSetter, text)); pane.add(bold, gbc); JCheckBox italic = new JCheckBox("Italic"); gbc.gridx = 0; gbc.gridy = 3; italic.addActionListener(new Italic(fontSetter, text)); pane.add(italic, gbc); JRadioButton times = new JRadioButton("Times", true); gbc.gridx = 1; gbc.gridy = 0; times.addActionListener(new Times(fontSetter, text)); pane.add(times, gbc); JRadioButton helvetica = new JRadioButton("Helvetica", false); gbc.gridx = 1; gbc.gridy = 2; helvetica.addActionListener(new Helvetica(fontSetter, text)); pane.add(helvetica, gbc); JRadioButton courier = new JRadioButton("Courier", false); gbc.gridx = 1; gbc.gridy = 4; courier.addActionListener(new Courier(fontSetter, text)); pane.add(courier, gbc); ButtonGroup fonts = new ButtonGroup(); //now only one of these buttons can be selected at once fonts.add(times); fonts.add(helvetica); fonts.add(courier); JButton ok = new JButton("OK"); gbc.gridx = 3; gbc.gridy = 2; //ok.addActionListener(); pane.add(ok, gbc); window.setVisible(true); } } </code></pre> <p>And here are my classes for my action listeners:</p> <pre><code>class Bold implements ActionListener { private final FontSetter fontSetter; private final JTextField textfield; Bold(FontSetter fontSetter, JTextField textfield) { this.fontSetter = fontSetter; this.textfield = textfield; } Font font; public void actionPerformed(ActionEvent e) { textfield.setFont(font.deriveFont(Font.BOLD)); } } class Italic implements ActionListener { private final FontSetter fontSetter; private final JTextField textfield; Italic(FontSetter fontSetter, JTextField textfield) { this.fontSetter = fontSetter; this.textfield = textfield; } public void actionPerformed(ActionEvent e) { textfield.setText(""); } } class BoldItalic implements ActionListener { private final FontSetter fontSetter; private final JTextField textfield; BoldItalic(FontSetter fontSetter, JTextField textfield) { this.fontSetter = fontSetter; this.textfield = textfield; } public void actionPerformed(ActionEvent e) { textfield.setText(""); } } class Times implements ActionListener { private final FontSetter fontSetter; private final JTextField textfield; Times(FontSetter fontSetter, JTextField textfield) { this.fontSetter = fontSetter; this.textfield = textfield; } public void actionPerformed(ActionEvent e) { textfield.setText("Times"); } } class Helvetica implements ActionListener { private final FontSetter fontSetter; private final JTextField textfield; Helvetica(FontSetter fontSetter, JTextField textfield) { this.fontSetter = fontSetter; this.textfield = textfield; } public void actionPerformed(ActionEvent e) { textfield.setText("Helvetica"); } } class Courier implements ActionListener { private final FontSetter fontSetter; private final JTextField textfield; Courier(FontSetter fontSetter, JTextField textfield) { this.fontSetter = fontSetter; this.textfield = textfield; } public void actionPerformed(ActionEvent e) { textfield.setText("Courier"); } } </code></pre> <p>I hope I have explained this clearly and would appreciate any help with my code, thanks.</p> <p>p.s also my fontsetter class this doesnt have any function atm but it was how I originally intended to layout my action listeners</p> <pre><code>class FontSetter { void setBold() { } void setItalic() { } void setBoldItalic() { } void setTimes() { } void setHelvetica() { } void setCourier() { } } </code></pre>
1
How to get an input value on a Visualforce page from an Apex controller?
<p>Let's pretend that I have an <em>sObject</em> called <em>MyCutomObject</em> with the fields <em>Column1</em>, <em>Column2</em>, <em>Column3</em>, <em>PickMeColumn</em> and others. The type of the <em>PickMeColumn</em> is <em>Picklist</em>.</p> <p>While it's easy to access the object's instance data in my page, I'm a bit stucked with how to get the user's input data from that page to be accessible inside the controller.</p> <p>Page code:</p> <pre><code>&lt;apex:page sidebar="false" standardController="MyCustomObject__c" extensions="MyCustomSearchController"&gt; &lt;apex:form &gt; &lt;apex:pageBlock title="Search Criteria"&gt; &lt;apex:pageBlockSection&gt; &lt;apex:inputField value="{!myObject.PickMeColumn__c}" /&gt; &lt;/apex:pageBlockSection&gt; &lt;apex:commandButton value="Search" id="SearchButton" action="{!search}"/&gt; &lt;/apex:pageBlock&gt; &lt;apex:pageBlock title="Search Results"&gt; &lt;apex:pageBlockTable value="{!myObjectList}" var="myObject"&gt; &lt;apex:repeat value="{!myObject}" var="aRecord"&gt; &lt;apex:column value="{!aRecord.Column1__c}"/&gt; &lt;apex:column value="{!aRecord.Column2__c}"/&gt; &lt;apex:column value="{!aRecord.Column3__c}"/&gt; &lt;/apex:repeat&gt; &lt;/apex:pageBlockTable&gt; &lt;/apex:pageBlock&gt; &lt;/apex:form&gt; &lt;/apex:page&gt; </code></pre> <p>Controller code:</p> <pre><code>public class MyCustomSearchController { public MyCutomObject__c myObject {get;set;} public List&lt;MyCutomObject__c&gt; myObjectList {get;set;} public MyCustomSearchController(ApexPages.StandardController controller) { } public PageReference search() { String ValueSelectedByUser = '??? Help!'; myObjectList = [SELECT Column1__c, Column2__c, Column3__c FROM MyCutomObject__c WHERE PickMeColumn__c = ValueSelectedByUser]; return ApexPages.currentPage(); } } </code></pre>
1
Loop through numbers from 0 to 100 and print out every third number without the modulo function using recursion
<p>I had an interview the other day that asked the question, loop through the numbers from 0 to 100 and print out every third number. This is a very easy question if you know what the modulo function is. So I came up with the solution (Note I was using Java): </p> <pre><code>for (int i=0; i&lt;100; i++) { if (i % 3 == 0) { System.out.println(i); } } </code></pre> <p>He then asked, what if you can't use division or the modulo function. So I had to think about this for about 30 seconds, and came up with a solution, that I knew was very inefficient, and let him know it was very inefficient, but would work. </p> <pre><code>int x = 3; for (int i=0; i&lt;100; i++) { for (int j=0; j&lt;33; j++) { if (x*j==i) { System.out.println(i); break; } } } </code></pre> <p>I'm free writing this without testing, so it might not work 100%, but you get the idea of how I solved the problem. He said he understood what I was trying to do. He then said that there is another way to do it using a recursive function. He tried to briefly explain it to me, but I didn't understand how you could use a recursive function to solve this problem. Can anyone come up with a solution using recursion?</p> <p>EDIT: </p> <p>Thanks for all the answers! I didn't think this question would attract as much attention as it did, but I appreciate all the answers. Some of you didn't understand that you can ONLY increment by 1. So you must loop through every natural number from 0 to 100. </p>
1
Image classification using SVM - Python
<p>I have a set of images classified as good quality image and bad quality image. I have to train a classification model so that any new image can be classified as good/bad. SVM seems to be the best approach to do it. I have done image processing in MATLAB but not in python.</p> <p>Can anyone suggest how to do it in python? What are the libraries? For SVM scikit is there, what about feature extraction of image and PCA?</p>
1
Redirection to external URL with POST parameters from Spring MVC
<p>For some subscription process, there is a requirement as follows :</p> <ol> <li>User visits our website</li> <li>For any subscription process, user click the relevant section that should redirect the view to specified external URL having POST parameters.</li> <li>External party handles the subscription</li> </ol> <p>It could be solved using <code>&lt;form/&gt;</code> defining the method=POST and putting all the required parameters in hidden fields.</p> <p>But, we have CMS in place so changing the already existing view to support <code>&lt;form/&gt;</code> would be cumbersome.</p> <p>I was hoping that there could be some solution that will allow in the following way:</p> <ol> <li>User visits the page</li> <li>User clicks the relevant section and sends the request to our internal mapping (along with some ID).</li> <li>Using that ID, will prepare the relevant payload and will redirect the view to external url along with that payload (using POST).</li> </ol> <p>Please let me know for more information.</p>
1
WooCommerce: Adding tax to old (completed) orders
<p>I have a little problem. A client of ours setup a WooCommerce shop himself and forgot to add taxes. Since he was in over his head he decided to get help setting it all up.</p> <p>Now unfortunately this shop is already live and has about 50 completed orders in it. I setup the taxes etc. correctly for him but this will work only for new orders, not the old ones.</p> <p>Does anybody know a simple way of adding the taxes to the old orders (all prices are including tax), maybe a loop or something I can run over the orders to get the taxes calculated?</p> <p>I tried something really simple, just constructing the order and calling calculate_taxes() but this will only add a tax of 0,00€ to the order, so I guess I'm missing something important here:</p> <pre><code>$order = new WC_Order(1234); $order-&gt;calculate_taxes(); </code></pre> <p>Thank you for your help</p>
1
NoNetworkAvailable: Unable to create the network. No tenant network is available for allocation
<p>I'm trying to setup a simple control+compute on a single ubuntu node. I'm using devstack. This is the command that fails:</p> <pre><code>neutron net-create --tenant-id 6fad6bf2ae9c49d3b19958abd59f3ce0 private-net </code></pre> <p>And the error is:</p> <pre><code>NoNetworkAvailable: Unable to create the network. No tenant network is available for allocation. </code></pre> <p>here's my relevant config ml2 config:</p> <pre><code>[ml2] tenant_network_types = flat extension_drivers = port_security type_drivers = flat mechanism_drivers = openvswitch [ml2_type_flat] flat_networks = public-physical-net,private-physical-net,dpdk-physical-net [ml2_type_vlan] network_vlan_ranges = private-physical-net [ml2_type_gre] tunnel_id_ranges = 1:1000 [ml2_type_vxlan] vni_ranges = 1001:2000 [ml2_type_geneve] [securitygroup] firewall_driver = neutron.agent.linux.iptables_firewall.OVSHybridIptablesFirewallDriver [agent] tunnel_types = root_helper_daemon = sudo /usr/local/bin/neutron-rootwrap-daemon /etc/neutron/rootwrap.conf root_helper = sudo /usr/local/bin/neutron-rootwrap /etc/neutron/rootwrap.conf [ovs] datapath_type = system bridge_mappings = public:br-ex </code></pre> <p>this is the ovs:</p> <pre><code>Bridge br-int fail_mode: secure Port br-int Interface br-int type: internal Port int-br-ex Interface int-br-ex type: patch options: {peer=phy-br-ex} Bridge br-ex Port br-ex Interface br-ex type: internal Port "p255p1" Interface "p255p1" Port phy-br-ex Interface phy-br-ex type: patch options: {peer=int-br-ex} ovs_version: "2.0.2" </code></pre> <p>The relevant section of local.conf:</p> <pre><code># Do not use Nova-Network disable_service n-net # Enable Neutron ENABLED_SERVICES+=,q-svc,q-dhcp,q-meta,q-agt,q-l3 Q_PLUGIN=ml2 Q_ML2_PLUGIN_MECHANISM_DRIVERS=openvswitch ## Neutron options FIXED_RANGE="10.0.123.0/24" NETWORK_GATEWAY=10.0.123.1 ##MY FLOATING_RANGE="10.0.0.0/22" Q_FLOATING_ALLOCATION_POOL=start=10.0.1.167,end=10.0.1.169 PUBLIC_NETWORK_GATEWAY="10.0.0.205" Q_USE_SECGROUP=True Q_L3_ENABLED=True PUBLIC_INTERFACE=p255p1 Q_USE_PROVIDERNET_FOR_PUBLIC=True OVS_PHYSICAL_BRIDGE=br-ex PUBLIC_BRIDGE=br-ex OVS_BRIDGE_MAPPINGS=public-physical-net:br-ex Q_ML2_PLUGIN_TYPE_DRIVERS=flat Q_ML2_TENANT_NETWORK_TYPE=flat ENABLE_TENANT_VLANS=False ENABLE_TENANT_TUNNELS=False PUBLIC_PHYSICAL_NETWORK=public-physical-net PHYSICAL_NETWORK=private-physical-net PUBLIC_NETWORK_NAME=public-net PRIVATE_NETWORK_NAME=private-net Q_ML2_PLUGIN_FLAT_TYPE_OPTIONS="flat_networks=public-physical-net,dpdk-physical-net,private-physical-net" # CH did not exist </code></pre>
1
How to send http header with data to rest Api codiegniter?
<p>I want to send http header to Api and get json response.</p> <p>I have all book detail in books table and I want to get all books.</p> <p>But i have 5 http header to get access them.</p> <p><strong>Client-Service,Auth-Key,Content-Type,User-ID,Authorization</strong></p> <p>Url to get details:</p> <p><a href="http://127.0.0.1/RestApi/index.php/book/" rel="nofollow">http://127.0.0.1/RestApi/index.php/book/</a></p> <p>Controller Code:</p> <pre><code> public function index() { $method = $_SERVER['REQUEST_METHOD']; if ($method != 'GET') { json_output(400, array('status' =&gt; 400, 'message' =&gt; 'Bad request.')); } else { $check_auth_client = $this-&gt;MyModel-&gt;check_auth_client(); if ($check_auth_client == true) { $response = $this-&gt;MyModel-&gt;auth(); if ($response['status'] == 200) { $resp = $this-&gt;MyModel-&gt;book_all_data(); json_output($response['status'], $resp); } } } } </code></pre> <p>Model Code:</p> <pre><code>public function book_all_data() { return $this-&gt;db-&gt;select('id,title,author')-&gt;from('books')-&gt;order_by('id','desc')-&gt;get()-&gt;result(); } </code></pre> <p>I want to access to access on button click but how send http header to rest api page and get all data using codeigniter ?</p>
1
Which php framework is good for shared hosting?
<p>I'm trying to use a PHP framework, but I don't have confidence with Composer and terminal commands. I would like to download a framework and upload it on my shared hosting and start to develop my application. Any suggestion?</p> <p>Thanks.</p>
1
Is there a way to enable the SO_REUSEADDR socket option when using System.Net.HttpListener?
<p>Been searching for this for over an hour now, and I have not found in documentation nor in examples on the web how to enable the <code>SO_REUSEADDR</code> option when working with the <code>HttpListener</code> class.</p> <p>My specific use case is within a Powershell script, but even if there is an answer in C#, that would be fine. This is about as cut-and-dry as it gets:</p> <pre><code>$Listener = New-Object System.Net.HttpListener $Listener.Prefixes.Add('http://+:9999/') Try { $Listener.Start() # While loop here to handle requests; omitted for brevity } Catch { # omitted here for brevity } </code></pre> <p>There are times where I <code>Ctrl-C</code> to break out of the script while testing, and leaving the loop this way does not allow <code>$Listener.Stop()</code> to be called and the socket properly closed. (Yes, I know - don't do this if it breaks things)</p> <p>Normally, when I need a listening socket, I make use of <code>SO_REUSEADDR</code> to handle those times where things don't clean up properly to allow me to restart my listener without having to wait 30 minutes for the port to be available again. Is there a way to do this with <code>HttpListener</code> and I'm just missing it?</p>
1
Merging dataframes together in a for loop
<p>I have a dictionary of pandas dataframes, each frame contains timestamps and market caps corresponding to the timestamps, the keys of which are: </p> <pre><code>coins = ['dashcoin','litecoin','dogecoin','nxt'] </code></pre> <p>I would like to create a new key in the dictionary 'merge' and using the pd.merge method merge the 4 existing dataframes according to their timestamp (I want completed rows so using 'inner' join method will be appropriate. </p> <p>Sample of one of the data frames: </p> <pre><code>data2['nxt'].head() Out[214]: timestamp nxt_cap 0 2013-12-04 15091900 1 2013-12-05 14936300 2 2013-12-06 11237100 3 2013-12-07 7031430 4 2013-12-08 6292640 </code></pre> <p>I'm currently getting a result using this code: </p> <pre><code>data2['merged'] = data2['dogecoin'] for coin in coins: data2['merged'] = pd.merge(left=data2['merged'],right=data2[coin], left_on='timestamp', right_on='timestamp') </code></pre> <p>but this repeats 'dogecoin' in 'merged', however if <code>data2['merged']</code> is not <code>= data2['dogecoin']</code> (or some similar data) then the merge function won't work as the values are non existent in 'merge'</p> <p>EDIT: my desired result is create one merged dataframe seen in a new element in dictionary 'data2' (data2['merged']), containing the merged data frames from the other elements in data2</p>
1
Maven WildFly Plugin: Could not execute goal deploy
<p>I want to deploy my war-files with the maven wildfly-plugin. I use the <code>wildfly-8.2.0.Final</code>-version and I was to force to change the port of the management-console to <a href="http://127.0.0.1:9990" rel="nofollow">http://127.0.0.1:9990</a>.</p> <p>This is my maven configuration:</p> <pre><code> &lt;plugin&gt; &lt;groupId&gt;org.wildfly.plugins&lt;/groupId&gt; &lt;artifactId&gt;wildfly-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.0.2.Final&lt;/version&gt; &lt;configuration&gt; &lt;jbossHome&gt;C:\wildfly-8.2.0.Final&lt;/jbossHome&gt; &lt;hostname&gt;127.0.0.1&lt;/hostname&gt; &lt;port&gt;8080&lt;/port&gt; &lt;serverConfig&gt;standalone-full.xml&lt;/serverConfig&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p>I get following error:</p> <pre><code>[INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.705 s [INFO] Finished at: 2016-02-01T22:46:43+01:00 [INFO] Final Memory: 21M/171M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.wildfly.plugins:wildfly-maven-plugin:1.0.2.Final:deploy (default-cli) on project wildfly: Could not execute goal deploy on C:\Users\laudatio\Documents\Java\wildfly\target\wildfly.war. Reason: I/O Error could not execute operation '{ [ERROR] "operation" =&gt; "read-attribute", [ERROR] "address" =&gt; [], [ERROR] "name" =&gt; "launch-type" [ERROR] }': java.io.IOException: Unknown service name [ERROR] -&gt; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException </code></pre> <p>Any suggestions?</p>
1
App to turn off airplane mode on android
<p>First little background why i need to write this app. My phone got wet and unfortunately screen doesn't work now (I can't see anything and I can't press anything). Phone has airplane mode turn on so my photos cannot synchronize. I cannot connect with USB cable because it is in "Only recharge state". USB debugging is turn off so I cannot connect with adb to turn off airplane mode. But there is a little light in a tunnel. There is WIFI working. I hear a sound when it connects to my network so I know it's working. My idea is to write a simple app that will turn off airplane mode. I'll install it from PC using Play Store but I need a way to turn it on. I think it can be done by registering this app as a listener to some system call. Can Play Store register app as a listener without a need to run this app?</p> <p>Do you think that's all possible? Maybe someone has other idea? </p> <p>Thanks!</p>
1
Purpose of sentinel values in merge sort
<p>I am currently taking my first algorithms class and we have recently begun talking about merge sort. Our professor showed us the pseudocode for merge sort with sentinel values, but did not really explain their purpose. I am still fairly confused as to what purpose they serve, as one of our homework problems is to write a merge sort without sentinel values. Are there any advantages or disadvantages to including sentinel values? Any help would be greatly appreciated.</p> <p>Edit: Just as a note, I have programmed a merge sort previously and did so without sentinel values, which is part of what has led to my confusion.</p>
1
Getting a stack trace I can use when using webpack
<p>This is a general question. Sometimes I get an error when developing with angular and webpack that the entire stack trace is lines from bundle.js or angular.js (sometimes jquery.js). Is it possible to see where the error actually came from (I mean in my code)?</p> <p>I've looked into devtool types in <a href="https://webpack.github.io/docs/configuration.html" rel="noreferrer">https://webpack.github.io/docs/configuration.html</a> but even when I use eval-source-map I can't get anything I can use (using <code>devtool:source-map</code> is out of the question because it's insanely slow).</p> <p>Thanks.</p>
1
Toggling between two buttons using jQuery
<p>I've seen a few articles about this dotted around but I cant seem to get their solutions to work for me.</p> <p>What I have are two buttons which control the show() and hide() states of different div's. On page load both of the div's are set to .hide() as the user doesn't need to see them until clicked.</p> <p>So, I have two buttons a and b which currently work perfectly however you can show() both div's at the same time which I don't want to happen. The current code resembles </p> <pre><code>$('#a-div).hide(); $('#b-div).hide(); $('#a').click(function(){ $('#a-div).toggle(500); }); $('#b').click(function(){ $('#b-div).toggle(500); }); </code></pre> <p>So how can I re-write this so that if #a-div is visible (already tried the .is(':visible') method) and #b is clicked nothing happens until #a-div is hidden again and vis versa? </p>
1
Sqlalchemy: Database delete error
<p>For the following function</p> <pre><code>def deleteMenuItem(restaurant_id,menu_id): if request.method == 'POST': item = session.query(MenuItem).filter_by(id = menu_id) session.delete(item) session.commit() return redirect(url_for('showMenu',restaurant_id =restaurant_id)) else: return render_template('deletemenu.html',restaurant_id=restaurant_id,menu_id=menu_id) </code></pre> <p>When I try to delete an item. I get the following error </p> <blockquote> <p>sqlalchemy.orm.exc.UnmappedInstanceError UnmappedInstanceError: Class 'sqlalchemy.orm.query.Query' is not mapped</p> </blockquote> <p>The error can be fixed if I do the following change to the code</p> <pre><code>item = session.query(MenuItem).filter_by(id = menu_id).one() </code></pre> <p>I am not sure why the .one() fixes the problem. Since the query itself will always find one result. So why is the .one() needed?</p>
1
How to call php function with <li> onclick event using AJAX?
<p>Could you help me how to call PHP function (which is calling an external server) by using AJAX if I am using <code>onclick</code> event?</p> <pre><code>&lt;div class="container"&gt; &lt;h3 style=color:blue;&gt;INFORMATION &lt;/h3&gt; &lt;ul class="nav nav-pills" style="background-color:lightblue" &gt; &lt;li class="dropdown"&gt; &lt;a class="dropdown-toggle" data-toggle="dropdown" href="#" style=color:blue;&gt; Information &lt;span class="caret"&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a onclick="get_inf1()" style="color:blue;cursor:pointer;"&gt;Submenu_1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a onclick="get_inf2()" style="color:blue;cursor:pointer;"&gt;Submenu_2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a onclick="get_inf3()" style="color:blue;cursor:pointer;"&gt;Submenu_3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>And the called php function's begin codes are:</p> <pre><code>&lt;?php function get_info1() { $bdy = "&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;"; $bdy.= "&lt;soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;"; $bdy.= "&lt;soap:Body&gt;"; $bdy.= "&lt;GetInformation xmlns=\"http:// website /\" /&gt;"; $bdy.= "&lt;/soap:Body&gt;"; $bdy.= "&lt;/soap:Envelope&gt;\r\n"; $req = "POST /data.asmx HTTP/1.1\r\n"; </code></pre> <p>etc ...</p>
1
Charles Proxy Windows 10 https: SSLHandshake: Remote host closed connection during handshake
<p>I am trying to see the https queries that are being fired by my windows 10 application.</p> <p>I have installed the Charles SSL certificate (under help-> SSL proxy -> install Charles Root certificate)</p> <p>And under SSL Proxing settings I have checked Enabe SS proxing and have also added my location : api.mywebsite.com</p> <p>however when i am looking at Charles i see: URL <a href="https://api.mywebsite.com" rel="nofollow">https://api.mywebsite.com</a> Status Failed Failure SSLHandshake: Remote host closed connection during handshake Notes You may need to configure your browser or application to trust the Charles Root Certificate. See SSL Proxying in the Help menu.</p> <p>but its not working has anyone have this issue?</p>
1
how to find the date range in uri request search in elasticsearch
<p>I have a search in which i need to find the delta of data <a href="http://localhost:9200/index/index_type/_search?q=sampledate[21-02-2015" rel="nofollow">http://localhost:9200/index/index_type/_search?q=sampledate[21-02-2015</a> TO 22-02-2015]</p> <p>but this search is giving me error could anybody help?</p>
1
Queue module error
<pre><code>#!/usr/bin/env python import threading import Queue import time from ftplib import FTP ftphostlist = ['ftp.x.org', 'ftp4.FreeBSD.org', 'ftp.ncsa.uiuc.edu', 'ftp.crans.org'] class WorkerThread(threading.Thread): def __init__(self, queue, tid): threading.Thread.__init__(self) self.lock = threading.Lock() self.queue = queue self.tid = tid print "Worker %d Reporting for Service Sir!" % self.tid def run(self): while True: host = None try: host = self.queue.get(timeout=1) #time.sleep(2) except Queue.Empty: print "Worker %d exiting..." % self.tid return #login to ftp host anonymously and list the dirs self.lock.acquire() try: conn = FTP(host) conn.login() print 'Host: ' + host time.sleep(2) print host + conn.retrlines('LIST') except: print "Error in listing" +host raise self.lock.release() self.queue.task_done() queue = Queue.Queue() threads = [] for i in range(1, 5): t = threading.Thread(target=WorkerThread, args=('Threads -1', 3)) t.start() print "Creating WorkerThread : %d" %i worker = WorkerThread(queue, i) worker.setDaemon(True) worker.start() threads.append(worker) print "WorkerThread %d Created!" %i time.sleep(.2) for host in ftphostlist: queue.put(host) queue.join() #wait for all the threads to exit for item in threads: item.join print "Scanning Complete!" </code></pre> <p>Hi, </p> <p>I am very new to python and was trying to make an FTP connecter as suggested by Pentesteracademy. I was working on an exercise which seemed to run correctly for a few times and then i get an error stating</p> <pre><code>"File "ftp_login.py", line 4, in &lt;module&gt; from Queue import * File "/media/sf_Python/Pentest/Queue.py", line 22, in &lt;module&gt; queue = Queue.Queue() TypeError: 'module' object is not callable" </code></pre> <p>I am not sure exactly where i went wrong but I have spent quite a few useless hours trying to figure it out. Sorry if the issue is simple I am just failing to see it </p>
1
Simple REST web server in docker container
<p>I would like a small web server that offers a REST api, that external tools can call to store very small amount of data (either write or read data) and offer a html page to display that data.</p> <p>The data would be a simple matrix (2d table). I was planning on having external tools sending a single entry of the data with the REST api (one square of the table) in json format (it will contain only about three strings). Maybe store the data in a xml file.</p> <p>I would like that web server to be in a docker container, so it can be deployed easily in our cloud environment (using a volume so in does not lose data). It would run under a Linux environment.</p> <p>I know this is kind of a broad question, but I would like to know what technology to use for that case. Should I use Python? I don't actually know how to do that. I did docker containers in the past for other things, did some REST api in JAVA, but nothing like this.</p> <p>Do you have suggestions or resources?</p>
1
Why create an empty class, then instantiate it and set some attributes?
<p><a href="http://www.aaronsw.com/2002/html2text/html2text.py" rel="nofollow">html2txt</a> contains the following code:</p> <pre><code>class Storage: pass options = Storage() options.google_doc = False options.ul_item_mark = '*' </code></pre> <p>I've not seen such an approach before. What's the benefit/use of this approach over setting up the attributes in <code>__init__()</code>, and is a class even necessary here?</p>
1
How to send command in Android via Bluetooth?
<p>I have a problem with send command to Bluetooth chip via Bluetooth.</p> <p>I have smartphone and BT chip paired good. because I can send "text" </p> <pre><code>BluetoothSPP bt; void Heat() { heat.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { bt.send("Text", true); } } ); } public void send(String data, boolean CRLF) { if(mChatService.getState() == BluetoothState.STATE_CONNECTED) { if(CRLF) data += "\r\n"; mChatService.write(data.getBytes()); } } </code></pre> <p>Heat is Button on xml file. Heat do Only thise code. </p> <p>But I don't know how I must remodel to prove send and receive these commands : </p> <p>↓</p> <pre><code>Send: "$$$" Receive: "CMD" Send: "S&amp;,0404\r" Receive: "AOK" Send: "S&amp;,0400\r" Receive: "AOK" Send: "---\r" Receive: "END" </code></pre> <p>I see so send text is successfully because chip have LED which turn-on if accept some information. </p> <p>Please give me advice or example.</p> <p>On create </p> <pre><code> protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_autoconnect); Log.i("Check", "onCreate"); bt = new BluetoothSPP(this); if(!bt.isBluetoothAvailable()) { Toast.makeText(getApplicationContext() , "Bluetooth is not available" , Toast.LENGTH_SHORT).show(); finish(); } bt.setBluetoothConnectionListener(new BluetoothConnectionListener() { public void onDeviceConnected(String name, String address) { Toast.makeText(getApplicationContext() , "Connected to " + name , Toast.LENGTH_SHORT).show(); } public void onDeviceDisconnected() { Toast.makeText(getApplicationContext() , "Connection lost" , Toast.LENGTH_SHORT).show(); } public void onDeviceConnectionFailed() { Log.i("Check", "Unable to connect"); } }); bt.setAutoConnectionListener(new BluetoothSPP.AutoConnectionListener() { public void onNewConnection(String name, String address) { Log.i("Check", "New Connection - " + name + " - " + address); } public void onAutoConnectionStarted() { Log.i("Check", "Auto menu_connection started"); } }); TextView btnConnect = (TextView)findViewById(R.id.btnConnect5); btnConnect.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (bt.getServiceState() == BluetoothState.STATE_CONNECTED) { bt.disconnect(); /** Toast.makeText(getApplicationContext() , "pripojene" , Toast.LENGTH_SHORT).show(); **/ // bt.disconnect(); } else { /** Toast.makeText(getApplicationContext() , "nepripojene" , Toast.LENGTH_SHORT).show(); **/ Intent intent = new Intent(getApplicationContext(), DeviceList.class); startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE); } } }); Log.i("Check", "onCreate"); textStatus = (TextView)findViewById(R.id.textStatus2); bt = new BluetoothSPP(this); if(!bt.isBluetoothAvailable()) { Toast.makeText(getApplicationContext() , "Bluetooth is not available" , Toast.LENGTH_SHORT).show(); finish(); } </code></pre> <p>I can comunicate with chip, but i don't know how i can send command. I think you just remodel <strong>bt.send..</strong> If? </p>
1
How to run this maven plugin task from command line?
<p>I see in <a href="https://github.com/codenvy/che-core/blob/55af13c6f03bd5eaae5f93f008add55b9c46bb07/ide/che-core-ide-app/pom.xml#L268-L280" rel="nofollow">this POM.xml</a>, there is some code using <code>exec-maven-plugin</code>:</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;IDEInjector-client&lt;/id&gt; &lt;phase&gt;generate-sources&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;java&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;mainClass&gt;org.eclipse.che.util.IDEInjectorGenerator&lt;/mainClass&gt; &lt;arguments&gt; &lt;argument&gt;--rootDir=${generated.sources.directory}&lt;/argument&gt; &lt;/arguments&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/plugin&gt; </code></pre> <p>I wonder is it possible to run it from command line? Because it seems generate some java classes which is used by other files.</p> <p><strong>Question</strong>: How can I run it if it's runnable?</p>
1
click() function on selenium not working in C#
<p>I am really fed up from this problem and not finding any solution.</p> <p>The problem is that I am trying to test a website using test automation in C#. For this I need to sign in, but the sign-in button is not actually a button, it's a span tag with property set <code>'role=button'</code>.</p> <p>I am using Selenium with Chrome web driver and using unit extensions to automate the test. The problem is whenever I run the test in Test Explorer the click event is performed, but the page does not navigate to next page, and nothing happens. However, when I set a break point and run the same test through <code>main</code> function it works fine.</p> <p>I have to set the break point to perform click operation and perform login operation.</p> <p>I am using a Visual Studio console application. Here is the <a href="http://i.stack.imgur.com/d8s9E.png" rel="nofollow">pic of my web site html tag</a>.</p>
1
Decrease the components size of Material UI
<p>I've been trying to figure out a way to decrease the fontSize to all the components set (<a href="http://www.material-ui.com/#/components" rel="noreferrer">http://www.material-ui.com/#/components</a>), they are too big for my taste, so I started creating a selectable list and using styles trying to decrease the fonts and sizes but I'm seeing isn't that easy.</p> <p>I've started with <strong>List</strong> and <strong>ListItem</strong>, I was able to reduce all the elements except the <strong>rightToggle</strong> element, I'm not seeing a way to override its style.</p> <p>Also I couldn't change the <strong>secondaryText</strong> font size.</p> <p>Is there a specific approach to achieve this without to much pain?, I'm seeing there are a lot of "magic" numbers hardcoded for the paddings and positioning, wouldn't be better make them overridable?</p> <p>Thanks</p>
1
Type error: Argument 1 passed to Symfony\Bridge\Twig\Extension\SecurityExtension::__construct() must be an instance of
<blockquote> <p>Type error: Argument 1 passed to Symfony\Bridge\Twig\Extension\SecurityExtension::__construct() must be an instance of Symfony\Component\Security\Core\SecurityContextInterface, instance of Symfony\Component\Security\Core\Authorization\AuthorizationChecker given, called in /path/to/project/var/cache/dev/appDevDebugProjectContainer.php on line 5090.</p> </blockquote> <p>I still continue to have this error but when I update my composer</p> <pre><code>composer update </code></pre> <p>all work right.</p> <p>How can I fix definitely it? Thanks.</p>
1
java spring repositories - findBy() method using set of IDs/values
<p>I have a java spring app. It does back end stuff, offering a Restful API, all using an Oracle database. </p> <p>For most resources, it follows a typical design pattern: "Controller > Service > Repository > DB".</p> <p>At the repository level, when extending the JpaRepository interface, one can define a set of methods without having to provide a body, just like this:</p> <pre><code>public interface SurgeryRepository extends JpaRepository&lt;Surgery, String&gt; { public List&lt;Surgery&gt; findByPracticeNameContainingIgnoreCase(String substring); public Surgery findById(String id); } </code></pre> <p>What i would like to know is how to define a method that allow me to retrieve multiple rows using a list of ids, something like:</p> <pre><code>public List&lt;Surgery&gt; findByIDs(List&lt;String&gt; IDs); </code></pre> <p>Something that should automatically map to this sort of SQL </p> <pre><code>SELECT * FROM SURGERIES WHERE SURGERY_ID IN ('101',102,103',104',105',106') </code></pre> <p>... but without having to write a native query in the java code. (and not necessarily for id, it could be for any field) Thanks in advance. </p>
1
AngularJS - Creating a floating scroll down/back to top button
<p>I'm running into an issue and I see no way out.</p> <p>I have one page app and I'm currently using angular-scroll for navigation. Now, what I'm trying to accomplish is the following:</p> <p>I have two "img" buttons one is ScrollDown and another is ScrollUp. Is there any way to create a directive as part of angular-scroll and/or AngularJS? when a user clicks on a ScrollDown button,It will scroll to the next div id (maybe place ids in some kind of array where the current location will be saved, therefore the click to trigger scroll to next array value in line) and when a user scrolls to the bottom, the button should change to ScrollUp and a click should return the user to the top of the page.</p> <p>I hope I have explained this well, any help would be greatly appreciated.</p> <p>P.S. just a note, the app is pure AngularJS, so there should be no jQuery dependency.</p> <p>EDIT</p> <p>I should also point out that I'm just learning Angular right now, so any help would be really appreciated.</p> <p>This is what I'm currently using for navbar nav:</p> <pre><code>var ScrollApp = angular.module('myApp.ScrollApp', ['duScroll', 'ngAnimate']).value('duScrollOffset', 60); ScrollApp.controller('ScrollCtrl', function($scope){ var container = angular.element(document.getElementById('container')); var sectionhome = angular.element(document.getElementById('Home')); $scope.toTheTop = function() { container.scrollTop(60, 5000); }; $scope.toHome = function() { container.scrollTo(sectionhome, 60, 1000); }; $scope.scrollVariable = false; } ); </code></pre> <p>Is there a way to append a directive to a controller below, that will contain an array of section anchors, add a location watch so when user clicks on the button, it takes him to a next div id in line and when he reaches the bottom, the button image to change and take user back to top.</p> <p>I hope that the question is properly formulated now.</p>
1
Java - Multiply Array Values into another Array
<p>I have an <code>int[]</code> array with x values (x can be defined by the user), the values are random ints between 1 and 9. Now I want to create another Array with the same amount of values, and each value of the new Array is the product of all values from the other Array, except the same index.</p> <p>So for example: </p> <ul> <li>Array1: <code>{4,3,5,7}</code></li> <li>Array2: <code>{3*5*7, 4*5*7, 4*3*7, 4*3*5} = {105, 140, 84, 60}</code></li> </ul> <p>Here's what I have:</p> <pre><code>public static int[] multiplyArrayValues (int [] values) { int array[] = new int[values.length]; for (int y = 0; y &lt; array.length; y++) { array[y] = 1; } /*for (int i = 0; i &lt; array.length; i++) { // wrong for (int z = 0; z &lt; x; z++) { if (z != i) { array[i] = array[i] * values[z]; } } }*/ return array; } </code></pre> <p>The difficulty is, I have to avoid for-loops in for-loops for performance. Which is why that one block is commented-out. Dividing is not allowed. </p>
1
Kafka - Docker - Error when sending message from Host to Container (Batch Expired)
<p>I'm having a difficult time troubleshooting, what should be a simple kafka-issue.</p> <p>I'm trying to publish a few messages from <code>kafak-console-producer</code>. When I type 'hi' I get:</p> <pre><code>/opt/kafka/bin/kafka-console-producer.sh --topic test --broker-list 172.17.0.21:9092 hi [2016-01-25 12:56:19,839] ERROR Error when sending message to topic test with key: null, value: 2 bytes with error: Batch Expired (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback) </code></pre> <p>I don't seem to be able to find any kafka-log4j-logs...</p> <p>I'm running the kafka server the way it is described in the <a href="http://kafka.apache.org/documentation.html#quickstart_startserver">quick-start</a></p> <p>I can create the topic &amp; describe it.</p> <p>One note which maybe important is that the kafka &amp; zookeeper are running in a docker-container (<code>172.17.0.21</code>) I'm creating the topic and sending messages from the host.</p> <hr> <p>Please note the both the (kafka-server) 9092 &amp; (zk) 2181 are open and accessible from the host, I've confirmed this using netstat &amp; telnet.</p>
1