input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Symfony Form div css class <p>Using Symfony 3 and building a form field like this:</p>
<pre><code>$builder
->add('tittle')
->add('price');
</code></pre>
<p>The result is something like:</p>
<pre><code><div>
<label ...></label>
<input ...>
</div>
</code></pre>
<p>and I want the result to include custom css classes in the wrapping <code>div</code>, like:</p>
<pre><code><div class='wrap-title'>
<label ...></label>
<input ...>
</div>
<div class='wrap-price'>
<label ...></label>
<input ...>
</div>
</code></pre>
<p>Trying to do as described <a href="http://symfony.com/doc/current/form/form_customization.html#what-are-form-themes" rel="nofollow">here</a> doesn't offer a way to add a class to the wrapping <code>div</code>, just the things inside it.</p>
<p>I don't want to use the bootstrap themes. I really need to add something of my own as a class there. Is that even possible?</p>
| <p>I hope this answer can helps you:</p>
<p>I do not think it's possible to create div element inside the formbuilder.</p>
<p>If you can use Twig then you can render each of the three parts of the field individually inside a div having your custom class</p>
<pre><code><div class=wrap-title"">
{{ form_label(form.title) }}
{{ form_errors(form.title) }}
{{ form_widget(form.title) }}
</div>
<div class=wrap-price"">
{{ form_label(form.price) }}
{{ form_errors(form.price) }}
{{ form_widget(form.price) }}
</div>
</code></pre>
|
Positioning an element in the top right corner of the parent element and ensuring wrapping around it <p>I would like to create a container for an arbitrary number of elements, with an expand/collapse button. The button should be in the top right corner of the container, and the elements inside the container should wrap around the button. Here's the idea:</p>
<p><a href="https://i.stack.imgur.com/ivS5M.png" rel="nofollow"><img src="https://i.stack.imgur.com/ivS5M.png" alt="enter image description here"></a></p>
<p>I made a quick <a href="http://codepen.io/azangru/pen/mAjkGX" rel="nofollow">Codepen prototype</a> of this element, but the only way I could come up with to position the button in the top right corner was <code>float: right</code>:</p>
<p>html:</p>
<pre><code><div class="container closed">
<button>Click</button>
<!-- some divs with class "child" inserted with js -->
</div>
</code></pre>
<p>css:</p>
<pre><code>.container {
height: 80px;
width: 330px;
margin: auto;
}
button {
float: right;
margin: 1.3em 1.6em 0 0;
}
.closed {
overflow-y: hidden;
}
.child {
width: 50px;
height: 30px;
background-color: grey;
display: inline-block;
margin: 1em;
}
</code></pre>
<p>So this seems to work with <code>float: right</code> but floats are so passé :-) Is there a cleaner way of positioning the button? I thought flexbox would be able to do it, but couldn't figure out a way of achieving this with flexbox. Any advice?</p>
<p><strong>UPD:</strong> Added the relevant html and css code.</p>
| <p>You can achieve this purely with CSS, if you use the <code>flex</code> property of CSS3's flexbox, just like you said. I made a small demo to prove the point.</p>
<p>The core part in CSS lies here:</p>
<pre><code> display: flex;
flex-flow: row-reverse wrap;
</code></pre>
<p>The <code>display: flex</code> will stretch the content across the width available and the <code>row-reverse</code> will align the items from right-to-left (where LTR is default). Read more <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes" rel="nofollow">about flexbox at MDN</a>. </p>
<p>The other part is the toggle of the height of the menu, I don't know how many items you (can) have, but in the demo I used a bit of vanilla JavaScript to expand and collapse the menu.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var mainNav = document.getElementById('menu-list');
var navToggle = document.getElementById('expandbutton');
function mainNavToggle() {
mainNav.classList.toggle('expanded');
}
navToggle.addEventListener('click', mainNavToggle);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu {
height: 60px;
}
.list,
.list-item {
list-style: none;
margin: 0;
padding: 0;
}
.list {
width: 100%;
display: flex;
flex-flow: row wrap;
height: 50px;
overflow: hidden;
}
.list-item {
width: 25%;
padding: 3px;
box-sizing: border-box;
}
.btn {
background-color: teal;
display: block;
padding: 10px;
box-sizing: border-box;
border-radius: 3px;
margin: 5px 0;
color: white;
text-decoration: none;
}
.top-right {
border: 0;
width: 100%;
display: block;
background-color: red;
}
.list.expanded {
height: 100px;
}
.list > .list-item:nth-last-child(n+4) ~ .list-button {
order: 1;
}
.list > .list-item:nth-child(n+4) {
order: 2;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
<ul class="list" id="menu-list">
<li class="list-item"><a href="#" class="btn">Button</a></li>
<li class="list-item"><a href="#" class="btn">Button</a></li>
<li class="list-item"><a href="#" class="btn">Button</a></li>
<li class="list-item"><a href="#" class="btn">Button</a></li>
<li class="list-item"><a href="#" class="btn">Button</a></li>
<li class="list-item"><a href="#" class="btn">Button</a></li>
<li class="list-item list-button">
<button href="#" id="expandbutton" class="btn top-right">Expand</button>
</li>
</ul>
</div></code></pre>
</div>
</div>
</p>
<p><strong>EDIT</strong></p>
<p>I updated the snippet with the <code>flexbox</code> property of <code>order</code> which really helps in this case (<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/order" rel="nofollow">MDN reference</a>).</p>
<pre><code>.list > .list-item:nth-last-child(n+4) ~ .list-button {
order: 1;
}
.list > .list-item:nth-child(n+4) {
order: 2;
}
</code></pre>
<p>The initial value of <code>order</code> is <code>0</code>. If you want to move the order around, it has to be higher than the initial value, so that's why we need to set the item of <code>.list-button</code> to <code>order: 1</code>. All the elements <em>after</em> the button needs to get behind or under the button (in case of 4 elements per row), so the <code>:nth-child(n+4)</code> needs an <code>order: 2</code>. See the updated snippet for a small demo.</p>
|
Java jdbc connect to mariadb on remote lan server <p>I know this has been asked a lot but after trying many solution found here I am stil unable to connect to my db.</p>
<p>I'm working on PC and I want to connect to mariadb mysql server on another machine in my LAN. But I want to do it in such a way that my program can connect to my mysql server from any place. Not only from this machine where mysql is or PC's in LAN. </p>
<p>I thought using my external IP and forwarding mysql port on router will do the trick, but I'm getting 'Communication failure' errors.</p>
<p>So far I made sure:</p>
<ul>
<li>-user, pass, db name are correct</li>
<li>-port is default 3306</li>
<li>-in mysql config I disabled bind-adress</li>
<li>-in mysql my user is allowed to connect from any host and from my external IP just to be sure...</li>
<li>-database is empty</li>
<li>-other databases are working, php can connect but it's executed on same server so it's connecting to 'localhost'</li>
<li>-DriverManager.getConnection("jdbc:mysql://MY_IP:3306/my_DB","javauser", "javauserpass");</li>
<li>-on machine where mysql server is installed (UbuntuServer) iptables arent configured</li>
<li>-I installed xampp and created db there. I can connect to this db using 'localhost' in login query string. But that makes my program to operate only locally. </li>
<li>-Inactive firewall doesn't change anything - still no connection</li>
</ul>
<p>Error:</p>
<pre><code>-------- MySQL JDBC Connection Testing ------------
MySQL JDBC Driver Registered!
Connection Failed! Check output console
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:989)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:341)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2251)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Main.main(Main.java:25)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
... 15 more
</code></pre>
<p>My example, testing program is taken from here: <a href="https://www.mkyong.com/jdbc/how-to-connect-to-mysql-with-jdbc-driver-java/" rel="nofollow">https://www.mkyong.com/jdbc/how-to-connect-to-mysql-with-jdbc-driver-java/</a></p>
<p>So where am I making mistake?</p>
| <p>Check for the MySQL/MariaDB <code>bind-address</code> variable in the configuration file for the database. <a href="https://mariadb.com/kb/en/mariadb/configuring-mariadb-for-remote-client-access/" rel="nofollow">Then configure it appropriately</a>. It's probably set up so that it's only binding to localhost.</p>
|
object created inside jQuery 'click' persists even though a new one is created <p>very new to JQuery so my code is probably not the best approach, so tips there would be nice...</p>
<p>But the problem is that the <code>reqObj</code> created inside the click function doesn't ever seem to be dismissed. If the function runs through and I console.log the object i get both the new one created and all the previous ones that were created as well. I tried putting the object outside the function but that doesn't work. I'm sure this is a quick fix. Thank you for any help.</p>
<p>P.S. the div's are created dynamically in javascript based on incoming data</p>
<pre><code>$(document).on('click', '.profileDiv', function(){
var outer = this;
$("#myModal").modal('toggle');
$('#headerModal').text('Would like to request a session with ' + $(outer).find('#pro_first_name').text());
$(document).on('click', '#modalRequest', function(){
var reqObj = {};
reqObj = {
pro_id : $(outer).attr('id'),
}
console.log(reqObj);
});
});
</code></pre>
| <p>You shouldn't really bind and event inside another event callback, and as you are using event delegation you don't really need to. What you are trying to do is pass data from the callback of one event to another.</p>
<p>You can achieve this through using global variables that all functions have access to, however this is an anti pattern as it can change at anytime by any piece of the code.</p>
<p>jQuery gives you a better way however to attach metadata to elements so you can easily transfer or store the state using <code>jQuery.fn.data</code> it's much better than resorting to global variables.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$.fn.modal = function(){}
$(document).on('click', '.profileDiv', function() {
var outer = this;
$("#myModal")
.data('reqObj', {
pro_id : $(outer).attr('id'),
})
.modal('toggle');
$('#headerModal').text(
'Would like to request a session with ' +
$(outer).find('#pro_first_name').text()
);
});
$(document).on('click', '#modalRequest', function(){
console.log($("#myModal").data());
});
$(document).on('keyup', '#messageReq', function(e){
var $modal = $('#myModal')
// get the data
var data = $modal.data()
// assign the text field value to the data
data.msg = this.value
// reset the data on the modal element
$modal.data(data)
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.profileDiv,
#modalRequest {
width: 200px;
height: 200px;
background: #bada55;
float: left;
margin: .5em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="profileDiv" id="myModal">profileDiv</div>
<div id="modalRequest">
modalRequest
<input id="messageReq"
type="text"
name="messageRequest"
placeholder="Present yourself" />
</div></code></pre>
</div>
</div>
</p>
|
Sails.js redirect with param <p>what is the best way to redirect inside a Sails.js Controller from one route to another and transfer some data at the same time.
My situation is that I've got one route that creates some data and the redirects back to another route. My problem is that I don't know how to transfer an error message (if one happens) back to the other route (because I want to display it there). </p>
<p>Bruno</p>
| <blockquote>
<p>My problem is that I don't know how to transfer an error message (if
one happens) back to the other route (because I want to display it
there).</p>
</blockquote>
<p>Sails@v0.12 includes flash middleware in form of <a href="https://github.com/jaredhanson/connect-flash" rel="nofollow">https://github.com/jaredhanson/connect-flash</a>:</p>
<pre><code>req.flash('error', payload);
res.redirect(307, '/');
return;
</code></pre>
<p>To get the error in another controller:</p>
<pre><code>var error = req.flash('error');
</code></pre>
|
Send a MySQL query when pressing checkbox with AJAX <p>I am trying to send an update query when a checkbox is pressed, using AJAX. How can I do this?</p>
<h3>HTML imports:</h3>
<pre><code><link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="js/checkbox.js"></script>
</code></pre>
<h3>HTML checkbox:</h3>
<pre><code><td>
<input type="checkbox" name="vehicle" value="" class="checkbox"> Ingevoerd<br>
</td>
</code></pre>
<p>(Yes my checkbox is in a table, I don't know if this has to be in a form.)</p>
<h3>JavaScript code:</h3>
<pre><code>$(".checkbox").change(function() {
window.alert(5 + 6);
$.ajax({
url: '../ingevoerd.php'
});
});
</code></pre>
<p>(the <code>window.alert</code> is not triggered when I press the checkbox)</p>
<h3>PHP code:</h3>
<pre><code>$stmt = $db->prepare('UPDATE table SET temp=0 where id = 1');
$stmt->execute();
var_dump('test');
</code></pre>
| <p>I guess your javascript code runs before your html exists, so when your browser is trying to find <code>$(".checkbox")</code>, there aren't any elements with the <code>checkbox</code> class yet.</p>
<p>You should have the code running only after the document is ready:</p>
<pre><code>$(function() {
$(".checkbox").change(function() {
window.alert(5 + 6);
$.ajax({
url: '../ingevoerd.php'
});
});
});
</code></pre>
<p>In the next example you can see that <strong>nothing will happen</strong> (because the javascript code exists before the elements are available in the DOM):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#d1').css('background', 'red');
</script>
<div id="d1">some block</div></code></pre>
</div>
</div>
</p>
<p>Same example, but wait for the DOM to be ready (this example <strong>will work</strong> as expected):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$('#d1').css('background', 'red');
});
</script>
<div id="d1">some block</div></code></pre>
</div>
</div>
</p>
|
How to know if a fraction will be rounded up when represented in floating point format (re: java remainder [%] results when using fp's) <p>Is there a simple way to tell whether a particular number gets rounded up in it's floating point representation? The reason I ask is related to a question I asked <a href="http://stackoverflow.com/questions/39859955/java-remainder-operator-gives-incorrect-results-with-floating-point-fractions-a">here</a> and a similar question was asked <a href="http://stackoverflow.com/questions/35529398/floating-point-arithmetic-and-numpy-remainder-function">here</a>, amongst others. </p>
<p>To recap, I was trying to ask why, for example, the expression 0.5 % 0.1 doesn't result in approximately zero but instead gives (approximately) 0.1. Many respondents blah on about how most numbers can't be exactly represented and so on but fail to actually explain why, for certain values, the result from the % operator is so far from zero when there <em>is no</em> remainder. It took me a long time to work out what was happening and I think it's worth sharing. Also, it explains why I've asked my question.</p>
<p>It seems that the % operator doesn't result is zero when it should if ths divisor is rounded up in it's floating point format but the dividend isn't. The division algorithm iteratively subtracts the divisor from the dividend until it would result in a negative value. The quotient is the number of iterations and the remainder is what's left of the dividend. It may not be immediately clear why this results in errors (it certainly wasn't to me) so I'll give an example.</p>
<p>For the 0.5 % 0.1 = (approximately) 0.1 case, 0.5 can be represented exactly, but 0.1 cannot <strong>and</strong> is rounded up. In binary 0.5 is represented simply as 0.1, but 0.1 in binary is 0.00011001100... repeating last 4 digits. Because of the way the floating point format works, this gets truncated to 23 digits (in single precision) after the initial 1. (See the much cited <a href="https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html" rel="nofollow">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a> for a full explanation.) Then it's rounded up, as this is closer to the 0.1(decimal) value. So, the values that the division algorithm works with are:</p>
<p>0.1 0000 0000 0000 0000 0000 000 --> 0.5 (decimal), and</p>
<p>0.0001 1001 1001 1001 1001 1001 101 --> 0.1 (decimal)</p>
<p>The division algorithm iterations are;</p>
<p>(1) 1.00000000000000000000000 - 0.000110011001100110011001101 = </p>
<p>(2) 0.011001100110011001100110011 - 0.000110011001100110011001101 =</p>
<p>(3) 0.01001100110011001100110011 - 0.000110011001100110011001101 =</p>
<p>(4) 0.001100110011001100110011001 - 0.000110011001100110011001101 =</p>
<p>(x) <strong>0.0001100110011001100110011</strong> - 0.000110011001100110011001101 =</p>
<p>-0.000000000000000000000000001</p>
<p>As shown, after the 4th iteration further subtraction would result in a negative, so the algorithm stops and the value of the dividend left over (in <strong>bold</strong>) is the remainder, the approximation of decimal 0.1.</p>
<p>Further, the expression 0.6 % 0.1 works as expected as 0.6 gets rounded up. The expression 0.7 % 0.1 doesn't work as expected and although 0.7 can't be represented exactly, it doesn't get rounded up.
I've not tested this exhaustively but I <em>think</em> this is what's going on. Which brings me (at last!) to my actual question:</p>
<p>Does anyone know of simple way to tell if a particular number will be rounded up? </p>
| <p>Let's consider the case when floats <code>a > b > 0</code>. Each float is a multiple of it's ulp and we can write:</p>
<p><code>a = na*ulp(a). ulp(a)=2^ea</code>. na is the integer significand of a. ea is its biased exponent.<br>
<code>b = nb*ulp(b). ulp(b)=2^eb</code>. nb is the integer significand of b. eb is its biased exponent.<br>
For normalized float, <code>2^p > na >= 2^(p-1)</code> where p is the float precision (p=53 bits for IEEE 754 double precision).</p>
<p>So we can perform (possibly large) integer division: <code>na*2^(ea-eb)=nb*q+nr</code><br></p>
<p>From which we deduce <code>na*2^(ea-eb)*2^eb = nb*2^eb*q+nr*2^eb</code>, that is <code>a=b*q+nr*2^eb</code>.<br>
In other words, nr is the integer significand of the float remainder and eb its biased exponent, before normalisation.</p>
<p>From this, we see that the remainder operation is exact, because obviously nr <= nb, so the remainder is representable as float. So strictly speaking, the remainder is never rounded up.</p>
<p>When quotient is rounded to nearest int rather than truncated, which is the IEEE remainder operation,</p>
<pre><code>a=b*q+r
</code></pre>
<p>then, the remainder can be negative <code>r<0</code><br>
In which case you are interested in:</p>
<pre><code>a=b*(q-1) + (b+r)
</code></pre>
<p>I presume that this case with a negative r forcing a <code>b+r</code>result is what you call rounded up. Unfortunately, there is no easy way to tell if the remainder will be negative without performing the operation, except maybe when nb is a power of two (2^(p-1) or less in case of gradual underflow).</p>
<p>But you seem to be interested in the specific case <code>a=i/10^j</code> and <code>b=1/10^j</code> but only have float approximation <code>float(i/10^j)</code> and <code>float(1/10^j)</code>. Assuming 10^j and i are representable exactly (j<23 in double precision and i<=2^53), then we have access to the representation error with a fused multiply add:</p>
<pre><code>ea=fma(10^j,float(i/10^j),-i). 10^j*float(a)=10^j*a+ea.
eb=fma(10^j,float(1/10^j),-1). 10^j*float(b)=10^j*b+eb.
</code></pre>
<p>You have <code>i*b=a</code><br>
Now you want to compare how it goes with float approximation so you just get the remainder:</p>
<pre><code>r = (a+ea/10^j)-i*(b+eb/10^j) = 1/10^j * ea - i/10^j * eb.
</code></pre>
<p>The float approximation could possibly work, but not allways:</p>
<pre><code>float(float(float(b)*ea) - float(float(a)*eb))
</code></pre>
<p>However, you'd much better use fma again:</p>
<pre><code>r = fma(-i,eb,ea)/10^j
</code></pre>
<p>The sign of the remainder will give you the side of the float approximation...<br>
Here we simplified a bit the problem because we didn't consider the case when the quotient could be off by more than 1. That should be OK because i < 2^53 but we did not prove it.<br>
And it's just an exercize of style, because we are replacing a simple expression by more complex ones.</p>
|
Hashmap value getting overwritten <p>I'm having my <code>Hashmap</code> as such as a global variable within my class:</p>
<pre><code>private Map<String, CodaReportDTO> dateAndDTO = new TreeMap<>(); //hashmap for date and the dto
</code></pre>
<p>So the value here is a <code>DTO</code> which has properties which I had to fill in an excel. I'm trying to fill up only one field (which is numOfTxn from the DTO) using the key (the date). So basically i'm trying to print out the values of the <code>DTO</code> per day.</p>
<p>This is my <a href="http://pastebin.com/m5PNzVfN" rel="nofollow">DTO class</a>.</p>
<p>I'm trying to add values here to the <code>hashmap</code> as such for the number of days in a month:</p>
<pre><code>private JSONObject postDataToElasticSearchForSuccessCount(String url, String operatorID) throws IOException, JSONException, ParseException {
/*JSONObject jsonObject = elasticSearchDataReceiver.getResults(url);
//getting the number of hits
JSONObject totalHits = jsonObject.getJSONObject("hits");
Object hitsCountForSuccessCount = totalHits.get("total");
String hitCountForSuccessCount = hitsCountForSuccessCount.toString();
if (Integer.parseInt(hitCountForSuccessCount) > 0) {
codaReportDTO.setNumOfTxn(Integer.parseInt(hitCountForSuccessCount));
}
return new JSONObject(jsonObject.toString());*/
JSONObject updatedJsonObject = null;
String jsonBody;
String monthName = Month.of(Integer.parseInt(excelMonth)).name();
int numberOfDaysInAMonth = Utilities.getNumberOfDaysForMonth(Integer.parseInt(excelYear), monthName);
//iterate over the month
for (int i = 1; i < numberOfDaysInAMonth; i++) {
String day = appendZeroToDay(i);
excelDateMonth = day + "-" + excelMonth;
Date excelMonthOriginal = new SimpleDateFormat("dd-MM").parse(excelDateMonth);
String formattedDate = String.valueOf(excelMonthOriginal);
String MonthOnly = formattedDate.substring(4, 7);
String DateOnly = formattedDate.substring(8, 10);
String dateAndMonthFinal = DateOnly + "-" + MonthOnly;
excelDateMonth = dateAndMonthFinal;
String input = "{ \n" +
" \"query\":{ \n" +
" \"query_string\":{ \n" +
" \"query\":\"api:\\\"smsmessaging\\\" AND operatorid:" + operatorID + " AND transactionOperationStatus:\\\"\\\" AND responsecode:(200 201) AND year:" + excelYear + " AND month:" + excelMonth + " AND day:" + day + "\"\n" +
" }\n" +
" },\n" +
" \"aggs\":{ \n" +
" \"total\":{ \n" +
" \"terms\":{ \n" +
" \"field\":\"userid\"\n" +
" },\n" +
" \"aggs\":{ \n" +
" \"grades_count\":{ \n" +
" \"value_count\":{ \n" +
" \"script\":\"doc['userid'].value\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}\n";
jsonBody = input;
JSONObject jsonObject = elasticSearchDataReceiver.getResult(url, jsonBody);
JSONObject totalHits = jsonObject.getJSONObject("hits");
Object hitsCountForSuccessCount = totalHits.get("total");
String hitCountForSuccessCount = hitsCountForSuccessCount.toString();
int hitCount = Integer.parseInt(hitCountForSuccessCount);
if (hitCount > 0) {
updatedJsonObject = jsonObject;
codaReportDTO.setNumOfTxn(hitCount);
dateAndDTO.put(dateAndMonthFinal, codaReportDTO);
}
}
return updatedJsonObject;
}
</code></pre>
<p>The hashmap adding part is at the bottom of the above snippet:</p>
<blockquote>
<p>dateAndDTO.put(dateAndMonthFinal, codaReportDTO);</p>
</blockquote>
<p>The key and the value is coming correctly in the above line. But when it tries to update the value for the new key, it replaces the other values of keys which have values with the new value. Where am I going wrong?</p>
<p>I've been trying this for the whole day after looking into other question here in the SO, but still couldn't get through. Any help could be appreciated. </p>
| <p>You are using the same instance of your DTO for all the map's entries. This is why, each change is reflected on all values. If you dont want changes to be overriden, you need to create a new instance for each of the map's keys.</p>
|
getchar() in a for loop condition <p>Consider following code:</p>
<pre><code>int main()
{
char c;
for(;(c=getchar())+1;)
printf("%c\n",c);
}
</code></pre>
<p>It gets characters what I enter in terminal and prints them. When I remove <code>+1</code> in condition, program works but it doesnt stop when <code>EOF</code> (Ctrl+D) signal. When I change it to <code>+2</code> same problem.</p>
<p>My question is how that <code>+1</code> work? Is it something related to <code>getchar()</code> or <code>for</code> loop?</p>
| <p>That is because the int value of <code>EOF</code> is <code>-1</code>, so what you're doing is loop until the expression<code>(c=getchar())+1</code>) gets the value 0 which is when you read <code>EOF</code> (where value of exrpession is: -1+1=0). Also as wll pointed out in the comments you should declare c as int since <code>getchar() returns int.</code></p>
|
How to customize WebView in Android <p>I want load data from <code>json</code> into <code>WebView</code>! for this job i should use custom <code>webView</code>! such as : <strong>custom Font, Background, Direction</strong> and more ... <br><br>
I write this codes for custom <code>webView</code> : </p>
<pre><code> String style = "@font-face {font-family: \"MyFont\";src: url('file:///android_asset/fonts/iran_sans_mobile.ttf');} " +
"body {background:#FFFFFF;} div,h1,h2,p,h3 { font-family:\"MyFont\";line-height:30px; " +
"text-align: justify; color: #2d2d2d ;direction: rtl}";
</code></pre>
<p>And this codes has set content into <code>webview</code> : </p>
<pre><code> if (content != null) {
post_content_web.getSettings().setJavaScriptEnabled(true);
WebSettings settings = post_content_web.getSettings();
settings.setDefaultTextEncodingName("utf-8");
String style = "@font-face {font-family: \"MyFont\";src: url('file:///android_asset/fonts/iran_sans_mobile.ttf');} " +
"body {background:#FFFFFF;} div,h1,h2,p,h3 { font-family:\"MyFont\";line-height:30px; " +
"text-align: justify; color: #2d2d2d ;direction: rtl}";
post_content_web.loadData(content, "text/html; charset=utf-8", "utf-8");
}
</code></pre>
<p>But i don't know how to set this customize into my <code>webview</code> !</p>
<p>How can i set this customize into <code>webview</code>? Thanks all <3</p>
| <p>Try this codes : </p>
<pre><code>if (content != null) {
post_content_web.getSettings().setJavaScriptEnabled(true);
WebSettings settings = post_content_web.getSettings();
settings.setDefaultTextEncodingName("utf-8");
String myCustomStyleString = "<style type=\"text/css\">@font-face {font-family: MyFont;src: " +
"url(\"file:///android_asset/fonts/iran_sans_mobile.ttf\")}body,* {font-family: MyFont; font-size: " +
"medium;text-align: justify;}</style>";
post_content_web.loadDataWithBaseURL("", myCustomStyleString + "<div style=\"direction:rtl\">"
+ content + "</div>", "text/html", "utf-8", null);
}
</code></pre>
|
How to Dynamically $set Field Name From Variable in Mongo Script <p>I'm working on a script that will run in the shell in MongoDB. I am only using pure Javascript not node.js or Meteor. I have an array that contains key and value pairs for field names and field values respectively. I'm trying to use the key value from the array as the field name in an update function.</p>
<pre><code>var USER_ID = 1234567
var myArray = [
{ key : "name.first.nickname", value : "Sammy" }
]
for(var i = 0; i < myArray.length; i++){
setFields(myArray[i].key, myArray[i].value)
}
function setFields(key, value){
db.nameCollection.update(
{user : USER_ID},
{
$set: {
key : value
}
}
)
}
</code></pre>
<p>The field name is always set to "key" instead of the key variable's value "name.first.nickname". Is there a way to do this? </p>
| <pre><code>function setFields(key, value){
var update = {$set:{}};
update.$set[key] = value;
db.Test.update(
{userId : userId},
update
);
}
var userId = "daniele";
var myArray = [
{ key : "dynamic_key_002", value : "Sammy" }
]
for(var i = 0; i < myArray.length; i++){
setFields(myArray[i].key, myArray[i].value)
}
</code></pre>
<p>Also - if you need to make a lot of update, maybe you can consider to bulk them instead of making query one-by-one.</p>
<p><em>MongoDB provides clients the ability to perform write operations in bulk. Bulk write operations affect a single collection. MongoDB allows applications to determine the acceptable level of acknowledgement required for bulk write operations.</em></p>
<p><a href="https://docs.mongodb.com/manual/core/bulk-write-operations/" rel="nofollow">https://docs.mongodb.com/manual/core/bulk-write-operations/</a></p>
|
How can this phantom type example possibly be valid? <pre><code>data Expr a
= C a
| Add (Int -> a) (Expr Int) (Expr Int)
| Eq (Bool -> a) (Expr Int) (Expr Int)
add = Add id
eq = Eq id
eval :: Expr a -> a
eval (C x) = x
eval (Add f e1 e2) = f (eval e1 + eval e2)
eval (Eq f e1 e2) = f (eval e1 == eval e2)
expr1 = (C 5 `add` C 1) `eq` C 6
main = print $ eval expr1
</code></pre>
<p>Coming from a different functional language, ever so often I get an inkling that I do not exactly get Haskell's type system and the above is one of those cases.</p>
<p>What the above does is emulate a GADT with phantom types, but not in a way I could have imagined it working. <code>Int -> a</code> and <code>Bool -> a</code> are supposedly proofs of what type is supposed to be here, but when I translated the above example in F# as expected, it did not work because one of the pattern matching branches returns a <code>bool</code> while the other returns an <code>int</code>.</p>
<p>Can anyone illuminate as to why this example is correct in Haskell?</p>
<p>Edit: Here is a further elaboration of the problem.</p>
<pre><code>data Expr a
= C a
| Add (Expr Int) (Expr Int)
| Eq (Expr Int) (Expr Int)
add = Add
eq = Eq
eval :: Expr a -> a
eval (C x) = x
eval (Add e1 e2) = eval e1 + eval e2
eval (Eq e1 e2) = eval e1 == eval e2
expr1 = (C 5 `add` C 1) `eq` C 6
main = print $ eval expr1
</code></pre>
<p>When I remove the <code>Int -> a</code> and <code>Bool -> a</code> parts, the example fails to typecheck.</p>
<p>But in the first example those functions can only be <code>id</code>, that is of type <code>Int -> Int</code> and <code>Bool -> Bool</code> respectively. Applying the proof function the ADTs are carrying around with them should do absolutely nothing to change that fact as they are <code>id</code> in the example and should logically fail to typecheck. Applying them should do absolutely nothing.</p>
<p>This is what I do not understand; as far as I am concerned this example is pretty much magical to me in terms of how types work.</p>
<p>Edit2: Here is the F# translation:</p>
<pre><code>type Expr<'a> =
| C of 'a
| Add of ((int -> 'a) * Expr<int> * Expr<int>)
| Eq of ((bool -> 'a) * Expr<int> * Expr<int>)
let inline id x = x
let inline add x y = Add(id,x,y)
let inline eq x y = Eq(id,x,y)
let rec eval (x: Expr<'a>) : 'a =
match x with
| C x -> x
| Add(f,x,y) -> f (eval x + eval y)
| Eq(f,x,y) -> f (eval x = eval y)
let expr = add (C 5) (C 1) |> eq (C 7)
let r = eval expr
</code></pre>
<p>In the above example, in the <code>eval</code> function <code>'a</code> is inferred to be of type <code>int</code> and as a result the last line fails to type check.</p>
| <p>Take a look at the following type:</p>
<pre><code>eval :: Expr a -> a
</code></pre>
<p>This says, "given a value of type <code>Expr a</code>, for any <code>a</code> at all, I can produce an <code>a</code>". Your implementation of <code>eval</code> needs to be a proof of this statement.</p>
<p>Going back to the definition of the <code>Expr</code> type</p>
<pre><code>data Expr a
= C a
| Add (Int -> a) (Expr Int) (Expr Int)
| Eq (Bool -> a) (Expr Int) (Expr Int)
</code></pre>
<p>we can see that the constructors <code>Add</code> and <code>Eq</code>, apart from containing two values of type <code>Expr Int</code>, also contain a function from <code>Int</code> or <code>Bool</code> to <code>a</code>. The important part here is that <em>this is the same <code>a</code> as in the type constructor</em>, therefore the type of the value contained in this field will constrain the type of the value as a whole. You can check this in ghci:</p>
<pre><code>λ. :t Add id
Add id :: Expr Int -> Expr Int -> Expr Int
λ. :t Eq id
Eq id :: Expr Int -> Expr Int -> Expr Bool
</code></pre>
<p>This also works in the other direction, meaning that if an expression of type <code>Expr Bool</code> is expected in some context, and you try to use the <code>Add</code> constructor to create this expression, the type of its first field <em>must</em> be <code>Int -> Bool</code>. Generalising this leads you to the conclusion: if an expression of type <code>Expr a</code> is expected in that context, and you attempt to create such an expression using the <code>Add</code> or <code>Eq</code> constructors, the function contained inside <em>must</em> be of type <code>Int -> a</code> or <code>Bool -> a</code>, respectively.</p>
<p>Therefore, the functions contained inside those constructors are <em>proof</em> that, no matter which concrete <code>a</code> is in question, you will be able to apply them to either an <code>Int</code> or a <code>Bool</code> to construct an <code>a</code>. This is true <em>by construction</em> since picking out a concrete function chooses which concrete <code>a</code> we are dealing with.</p>
<p>Finally, going back to the implementation of <code>eval</code>:</p>
<pre><code>eval :: Expr a -> a
eval (C x) = x
eval (Add f e1 e2) = f (eval e1 + eval e2)
eval (Eq f e1 e2) = f (eval e1 == eval e2)
</code></pre>
<p>Let's examine the three branches to check whether it is indeed a proof of the we set out to prove, which was "given a value of type <code>Expr a</code>, for any <code>a</code> at all, I can produce an <code>a</code>":</p>
<ul>
<li>For the <code>C</code> branch this is trivially true since <code>x :: a</code>.</li>
<li>For the <code>Add</code> branch, we can determine that the type of <code>eval e1 + eval e2</code> must be <code>Int</code>. Luckily, we have <code>f :: Int -> a</code> which, by construction, is able to give us an <code>a</code> from an <code>Int</code> so this case is proved.</li>
<li>For the <code>Eq</code> branch, <code>eval e1 == eval e2</code> clearly has the type <code>Bool</code> (due to <code>(==)</code>). Again, we have <code>f :: Bool -> a</code> which is able to produce an <code>a</code> from this <code>Bool</code> and satisfy the type.</li>
</ul>
<p>Therefore, given a value of type <code>Expr a</code> constructed via any of its constructors, we are able to produce an <code>a</code> without knowing what concrete <code>a</code> we are talking about.</p>
<p>Also, keep in mind that since <code>eval</code> is polymorphic in <code>a</code>, different calls of <code>eval</code> <em>can</em> return values of different types, but the above should demonstrate that for a single call, all three branches are constrained to return the same type.</p>
|
In racket how do I replace word in string using string->list or list->string function only? <p>So I was practicing racket beginner language when I came along this question.</p>
<p>Write a function <code>str-replace</code> which consumes a string, a target character, and a
replacement character. The function produces a new string, which is identical to the consumed string with all occurrences of the target character (if any) replaced with the replacement character. For example, <code>(string-replace "word" #\o #\y) â "wyrd"</code>. </p>
<p>Note:
I may not use any built-in string functions other than <code>string->list</code> and <code>list->string</code>.</p>
<p>So I started with the code now I got stuck, how do I use wrapper function for this code as far now I have only this</p>
<pre><code>;; los is list of string
(define(str-replace los)
(+(first los)
(first (rest los))
(first (rest (rest los)))
(first (rest (rest (rest los))))))
</code></pre>
| <p>Define a conversion function which operates on lists:</p>
<pre><code>(define (replace-in-list input-list from-char to-char)
(if (null? input-list)
...
(cons ...
(replace-in-list ... from-char to-char))))
</code></pre>
<p><sup>(You have to fill the blank <code>...</code>)</sup></p>
<p>And call it from another one:</p>
<pre><code>(define (str-replace input-string from-char to-char)
(list->string
(replace-in-list
(string->list input-string) from-char to-char)))
</code></pre>
|
Ionic - Firebase : Get Current Time and Disable Past Dates <p>I am working on a project where you book hotel reservations.In the add booking page, I have an input datetime-local where the user selects the date and the time of the booking.</p>
<p>I want to get the online time and not use the device time to disable the user from booking past datetimes.</p>
<p>I tried to get the server time Timestamp from Firebase but did not know how to work with it.</p>
<p>I want to know what is the best way to deal with this issue.</p>
| <p>For firebase3, use firebase.database.ServerValue.TIMESTAMP</p>
<pre><code>$scope.createdDate = firebase.database.ServerValue.TIMESTAMP
</code></pre>
<p><a href="https://www.firebase.com/docs/web/guide/offline-capabilities.html#server-timestamps" rel="nofollow">doc is available here</a> </p>
<p>and for date time picker go for <a href="http://www.dotnetlearners.com/blogs/view/98/JQuery-Date-Picker-example-to-disable-previous-dates.aspx" rel="nofollow">this</a> code.</p>
|
AppEngine deployment error: java.lang.UnsupportedClassVersionError <p>I donât know what changed. This is an api that I have on AppEngine. For the past two days I have not been able to push. Does anyone know what may be causing this? I am using Android Studio on Mac El Capitan.</p>
<pre><code>Failed startup of context com.google.apphosting.utils.jetty.RuntimeAppEngineWebAppContext@6c5c4442{/,/base/data/home/apps/s~myapi-mobile/1.123456789034567}
org.mortbay.util.MultiException[java.lang.UnsupportedClassVersionError: org/apache/jsp/editor_005fform_jsp : Unsupported major.minor version 52.0, java.lang.UnsupportedClassVersionError: org/apache/jsp/editor_005fform_jsp : Unsupported major.minor version 52.0]
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:656)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:203)
at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:176)
at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:133)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:501)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:446)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:453)
at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:276)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:312)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:304)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:450)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:235)
at java.lang.Thread.run(Thread.java:745)
java.lang.UnsupportedClassVersionError: org/apache/jsp/editor_005fform_jsp : Unsupported major.minor version 52.0
at com.google.appengine.runtime.Request.process-9f0a91645afbfd1f(Request.java)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:820)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.lang.ClassLoader.loadClass(ClassLoader.java:375)
at org.mortbay.util.Loader.loadClass(Loader.java:91)
at org.mortbay.util.Loader.loadClass(Loader.java:71)
at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:73)
at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:446)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:453)
at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:276)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:312)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:304)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:450)
at java.lang.Thread.run(Thread.java:745)
java.lang.UnsupportedClassVersionError: org/apache/jsp/editor_005fform_jsp : Unsupported major.minor version 52.0
at com.google.appengine.runtime.Request.process-9f0a91645afbfd1f(Request.java)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:820)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.lang.ClassLoader.loadClass(ClassLoader.java:375)
at org.mortbay.util.Loader.loadClass(Loader.java:91)
at org.mortbay.util.Loader.loadClass(Loader.java:71)
at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:73)
at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:446)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:453)
at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:276)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:312)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:304)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:450)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
| <p>The error message you received:</p>
<pre><code>Unsupported major.minor version 52.0
</code></pre>
<p>just confirms that the JRE used on the Google App Engine cannot handle the bytecode version you tried to run:</p>
<p>52.0 means: <strong>Java SE 8 = 52 (0x34 hex)</strong></p>
<p>This is indeed cannot be handled, The App Engine currently works with Java7 Runtime (<a href="https://cloud.google.com/appengine/docs/java/runtime" rel="nofollow">see doc</a>):</p>
<blockquote>
<p>App Engine runs your Java web application using a Java 7 JVM in a safe "sandboxed" environment.</p>
</blockquote>
<p>But this is not a blocking issue. The only thing you need to do is just explicitly setting the compiler flags to 7, so that the produced bytecode remains compatible with Java7 JRE:</p>
<pre><code>-source 1.7 -target 1.7
</code></pre>
|
How to add more space between tabs in TabPane with css? <p><a href="https://i.stack.imgur.com/TB6Vy.png" rel="nofollow">I need to add more a gap between tabs with css in JavaFX</a></p>
| <p>Sorry this might not be exactly what you need but by simply hard-coding a tab in between the visible tabs and settings its opacity to 0.</p>
<pre><code>Tab bufferTab = new Tab();
bufferTab.setDisable(true);
bufferTab.setStyle("-fx-opacity: 0");
tabPane.getTabs().addAll(visibleTab1,bufferTab,visibleTab2,bufferTab,visibleTab3);
</code></pre>
<p>I hope this helps.</p>
|
node's module function return value empty/undefined? <p>I'm trying to get the html encoded table row value, returned from the slqLite based logger. As I'm new to node modules I'm stuck at:</p>
<pre><code>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
var html = '';
module.exports = {
readHtml: function() {
var html = ''; // optional but does not work here as well
db.serialize(function() {
db.each("SELECT rowid AS id, info FROM logger", function(err, row) {
html = html + '<tr><td>' + row.info + '<td><tr>'; << html is growing
console.log('Log: ' + row.info); << working
});
});
console.log(html); // html gets empty here!
return html;
}
}
</code></pre>
<p>So have no value returned from:</p>
<pre><code>var sysLog = require('logger');
sysLog.init();
sysLog.write('test string1');
sysLog.write('test string2');
console.log(sysLog.readHtml());
</code></pre>
<p>It has to be very simple to be solved ...
node is 6.7</p>
| <p>You problem is directly related to a very common issue when starting with JavaScript:</p>
<p><a href="http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call">How do I return the response from an asynchronous call?</a></p>
<p>Which shows the simplest way to receive results of an asynchronous operation, such as <code>db.each</code> is using a callback. </p>
<pre><code>function readHtml()
var html = ''
db.serialize(function() {
db.each(..., function(err, row) {
// this line executes sometime later
// after we already returned from readHtml()
});
});
// this line executes right after the call to db.serialize
// but before db.each calls the callback we give to it.
// At this point, html is '' because we still didn't read any rows
// (they are read asynchronously, sometime later)
return html;
}
readHtml(); // <-- this is always '' because rows are read at a later point
</code></pre>
<p>To solve this, you would need a function that will be called with a callback like this:</p>
<pre><code>readHtml(function(html) { // <-- this callback gets called once all rows are read
console.log(html);
});
</code></pre>
<p>Your situation also has an additional complication that <code>db.each</code> calls its callback once for every row. By looking at the <a href="https://github.com/mapbox/node-sqlite3/wiki/API#databaseeachsql-param--callback-complete" rel="nofollow">docs</a>, you can see that <code>db.each</code> accepts an additional <code>complete</code> callback when all rows are read. You can use this callback to signalize reading is done and pass the <code>html</code> results.</p>
<p>Here's how you can define <code>readHtml</code>:</p>
<pre><code>function readHtml(callback) { // pass in a callback to call once all rows are read and all html is accumulated
var html = '';
db.serialize(function() {
// read all the rows and accumulate html as before
db.each("SELECT rowid AS id, info FROM logger", function(err, row) {
html = html + '<tr><td>' + row.info + '<td><tr>';
}, function() {
callback(html); // use the second callback to signal you are done and pass the html back
});
});
}
</code></pre>
|
D3 axis origin changes as per its scales range <p>I am a little confused on how D3s axis object takes its origin position and where it is anchored(I assume its top left)</p>
<p>Also it seem like the origin point changes as per the range of the associated scale for instance,the two axis below would start at different position</p>
<p>1st axis</p>
<pre><code> //Xscale with scale not augmented
var stageXScale=d3.scaleLinear()
.domain([0,150])
.range([0,150]);
var stageXAxis = d3.axisBottom(stageXScale) //unaug axis
.ticks(20);
</code></pre>
<p>2nd axis</p>
<pre><code> //scale which is augmented
var stageXScaleAug=d3.scaleLinear()
.domain([0,stageWidth])
.range([0+stageMarginLeft,150+stageMarginLeft]);
var stageXAxisAug = d3.axisBottom(stageXScaleAug) //aug axis
.ticks(20);
</code></pre>
<p>Isn't the origin of the axis mapped to the origin of the parent container,if so why does the scale of the axis change this.
Here is Js fiddle example :</p>
<p><a href="https://jsfiddle.net/Snedden27/3wsx8bdy/12/" rel="nofollow">https://jsfiddle.net/Snedden27/3wsx8bdy/12/</a></p>
| <p>The position of the origin of the axis (prior to <code>transform</code>) is determined by the minimum value of the range of the scale.</p>
<p>For axis 1, the range is <code>[0,150]</code> and the axis starts at screen x-coordinate <code>0</code> of the parent element. (The axis ends at x-coordinate 150.)</p>
<p>For axis 2, the range is <code>[0+stageMarginLeft,150+stageMarginLeft]</code>, so that axis starts at screen x-coordinate <code>stageMarginLeft</code> (20) of the parent element.</p>
|
Android List View, In Alert Dialog Showing Same Item <p>I have created an Alert Dialog which shows a list view of addresses that the user has searched. However when the alert dialog is shown with the list view items, I get same item repeated, so if I got 6 addresses i'll get item 3 in the address collection repeating 6 times. </p>
<p>I have debugged, and the address collection does show unique items, however something is going wrong in between creating the dialog, and setting the adapter for the listview. I think it is something to do with the convertView in the AddressRowAdapter class, but I am not too sure.</p>
<p>Here is the code.</p>
<p>This is the SearchLocation class, the resource_address_listview contains a ListView widget, which is in a RelativeLayout</p>
<pre><code>//set our adapter
AddressRowAdapter dataAdapter = new AddressRowAdapter(getActivity(), addressList);
//Create Address Selection Dialog
AlertDialog.Builder addressSelectionDialog = new AlertDialog.Builder(getActivity());
//Get the layout file
LayoutInflater alertDialogInflater = getActivity().getLayoutInflater();
//Get our custom view
View getAlertDialogView = alertDialogInflater.inflate(R.layout.resource_address_listview,null);
//Set our custom view
addressSelectionDialog.setView(getAlertDialogView);
//Set up, confirmation buttons and events for dialog
addressSelectionDialog.setPositiveButton("Select", new AlertDialogPositiveButtonClick());
addressSelectionDialog.setNegativeButton("Cancel", new AlertDialogCancelButtonClick());
//Set up our adapter
//Get our list view
listViewAddressList = (ListView)getAlertDialogView.findViewById(R.id.listViewAddressList);
listViewAddressList.setAdapter(dataAdapter);
//listViewAddressList.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//Single choice mode, radio buttons
listViewAddressList.setOnItemClickListener(new AddressListViewOnItemClick());//Set our item click listener.
//Create and show dialog
createDialog = addressSelectionDialog.create();
createDialog.show();
</code></pre>
<p>Here is the code for the AddressRowAdapter, I believe something here is wrong but I can't see anything wrong with the code.</p>
<p>public class AddressRowAdapter extends ArrayAdapter {</p>
<pre><code>//Initialize private variables.
private Context context;
private List<Address> addresses;
private LayoutInflater inflater;
public AddressRowAdapter(Context context, List<Address> objects) {
super(context, 0, objects);
this.context = context;
this.addresses = objects;
this.inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//Setup location variables.
String _county = "";
String _subCounty = "";
String _country = "";
String _countryCode = "";
String _postcode = "";
String _addressLine="";
String _seperator = " ";
String _comma = ",";
//If no view is provided, get the view
if (convertView == null) {
convertView = inflater.inflate(android.R.layout.select_dialog_singlechoice, parent, false);
}
//Find all controls in view.
TextView textView = (TextView) convertView.findViewById(android.R.id.text1);
//loop through all the addresses.
for (int i=0;i<addresses.size();i++)
{
//Get address.
Address thisAddress = addresses.get(i);
//if it has no long/lat coordinates we do not need it.
if (!thisAddress.hasLatitude() && !thisAddress.hasLongitude())
break;
if (thisAddress.getAddressLine(0) != null)
_addressLine = thisAddress.getAddressLine(0) + _seperator;
if (thisAddress.getAdminArea() != null)
_county=thisAddress.getAdminArea() + _comma;
if(thisAddress.getSubAdminArea() != null)
_subCounty=thisAddress.getSubAdminArea() + _seperator;
if (thisAddress.getPostalCode() != null)
_postcode = thisAddress.getPostalCode() + _seperator;
if (thisAddress.getCountryCode() != null)
_countryCode=thisAddress.getCountryCode() + _comma;
if (thisAddress.getCountryName() != null)
_country = thisAddress.getCountryName();
textView.setText(_addressLine + _county + _subCounty + _postcode + _countryCode + _country);
}
return convertView;
}
@Nullable
@Override
public Address getItem(int position) {
return addresses.get(position);
}
@Override
public long getItemId(int position) {
return super.getItemId(position);
}
@Override
public int getCount() {
return addresses.size();
}
</code></pre>
<p>}</p>
<p>I have debugged this countless times, and the address collection always shows unique items, and I don't seem to be overwriting/replacing them, so I am completely lost to what is going on.</p>
<p>Any help would be appreciated</p>
<p>Kind regards</p>
| <p>Why are you using for loop in Adapter? There is no need of for loop. You can directly use </p>
<pre><code>Address thisAddress = addresses.get(position);
</code></pre>
<p>Adapter will create the view for the number of count returned by <strong>getCount()</strong> method. So, if you are returning correct count it will automatically create view for all addresses.</p>
<pre><code>public int getCount(){
return addresses.size();
}
</code></pre>
|
retrieving pointer to object from stack <p>I have problem with a stack of pointers. I have stack of pointers named ob1</p>
<pre><code>stack<object*> ob1;
</code></pre>
<p>then I create some pointer to object and pushed into stack. when I want retrieve these pointer from stack
I use this method;</p>
<pre><code>object * tag;
tag = new object();
tag = ob1.pop();
</code></pre>
<p>but I get "<code>error C2440: cannot convert void to object*</code>"
I am confuse what is wrong.
I would appreciate for any help. </p>
| <p>You get this error, because pop doesn't return anything.</p>
<p>See <a href="http://www.cplusplus.com/reference/stack/stack/pop/" rel="nofollow">here</a>, the return type is <code>void</code>, nothing.
You'll need the <code>top ()</code> member to get the element.
N.B. pop () will call the destructor of your element.</p>
|
Implementing specific count query in php <pre><code>class memberclass {
function Available()
{
if(!$this->DBLogin()) {
$this->HandleError("Database login failed!");
return false;
}
$ux = $_SESSION['username_of_user'];
$qry = "Select (one='Not done') + (two='Not done') + (three='Not done') + (four='Not done') + (five='Note done') As num_not_done From $this->tablename Where username='$ux'";
$result = mysqli_query($this->connection, $qry);
$result_length = mysqli_num_rows($result);
echo "$result_length";
}
}
</code></pre>
<p>I'm trying to show the amount of available items. So for every column where the value is "Not done" for a user it should sum it up in the query to form the total amount of "Not done" items. However when I try to show this number with the following code, I get the value "1" for each user for some reason:</p>
<pre><code><?= $memberclass->Available(); ?>
</code></pre>
| <p>You need cast the expressions to INT and then sum them. For MySQL database your query could look like this:</p>
<pre><code>SELECT (CAST(one='Not done' AS UNSIGNED) +
CAST(two='Not done' AS UNSIGNED) +
CAST(three='Not done' AS UNSIGNED) +
CAST(four='Not done' AS UNSIGNED) +
CAST(five='Not done' AS UNSIGNED)) as num_not_done
FROM tableName WHERE username = 'something'
</code></pre>
|
Composite key with manual increment <p>How do I, in a multiple session / transaction environment, safely insert a row into a table containing a primary composite key with a (manual) increment key.</p>
<p>And how do I get hold of the latest incremented value of <code>column_c</code>, <code>LAST_INSERT_ID()</code> don't return the desired value.</p>
<p>I have looked into <code>SELECT FOR UPDATE ... INSERT</code> and <code>INSERT INTO SELECT</code> but can't decide on which to use.</p>
<p>What is the best way to achieve this in terms of transaction safety (lock), isolation level and performance standpoint.</p>
<p><strong>Update</strong> - Another take on the problem</p>
<hr>
<p>Lets say two transactions / sessions try to insert the same column_a, column_b pair (example 1,1) simultaneously. How do I;</p>
<ol>
<li><p>Execute the insert queries in sequence. The first insert (transaction 1) should result in a composite key of 1,1,<strong>1</strong>, and the second (transaction 2) 1,1,<strong>2</strong>. I need some sort of locking mechanism</p></li>
<li><p>Retrieve the column_c value of the insert. I probably need to utilize variables?</p></li>
</ol>
<hr>
<p><strong>Table definition</strong></p>
<pre><code>CREATE TABLE `table` (
`column_a` int(11) unsigned NOT NULL,
`column_b` int(11) unsigned NOT NULL,
`column_c` int(11) unsigned NOT NULL,
PRIMARY KEY (column_a, column_b, column_c)
) ENGINE=InnoDB;
</code></pre>
<p><strong>Exempel data</strong></p>
<pre><code>+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 1 | 3 |
| 2 | 1 | 1 |
| 2 | 1 | 2 |
| 2 | 1 | 3 |
+----------+----------+----------+
</code></pre>
<p><strong>Take on the insert into select query</strong></p>
<pre><code>INSERT INTO `table` (`column_a`, `column_b`, `column_c`)
SELECT 2,1, IFNULL(MAX(`column_c`), 0) + 1 FROM `table`
WHERE `column_a` = 2 and `column_b` = 1;
</code></pre>
| <pre><code>BEGIN;
SELECT @c := MAX(c) + 1
FROM t
WHERE a = ? AND b = ?
FOR UPDATE; -- important
INSERT INTO t (a,b,c)
VALUES
(?, ?, @c);
COMMIT;
</code></pre>
<p>The hope is that the <code>FOR UPDATE</code> will stall until it can get a lock and the desired <code>c</code> value. Then the rest of the transaction should go smoothly.</p>
<p>I don't think that the setting of <code>transaction_isolation</code> matters, but that is worth studying.</p>
|
How to correctly use {$smarty.server.HTTP_HOST}{$smarty.server.REQUEST_URI} in Smarty? <p>I have a blog page in my website, which uses Smarty to create the posts, and I want to add a WhatsApp share button to them using it. I already searched on the whole internet, and I found this:</p>
<pre><code>{$smarty.server.HTTP_HOST}{$smarty.server.REQUEST_URI}
</code></pre>
<p>I am trying to use this right now in my blog.tpl file:</p>
<pre><code><a class="whatsapp" href="whatsapp://send?text={$smarty.server.HTTP_HOST}{$smarty.server.REQUEST_URI}">Compartilhar</a>
</code></pre>
<p>What's wrong with my code, and how could i fix it?</p>
| <p>Your code doesn't work because of several reasons:</p>
<ul>
<li><p>The obvious one is that the message you generate is not an URL. It reads something like: <code>stackoverflow/questions/40062450/...</code>. An URL starts with a protocol (usually <code>http://</code>). The text you send should be:</p>
<pre><code>http://{$smarty.server.HTTP_HOST}{$smarty.server.REQUEST_URI}
</code></pre></li>
<li><p>An URL (as the one generated by the above code) contains special characters that must be encoded when it is used as an argument in another URL (f.e. <code>&</code>). Failing to properly encode <code>&</code> when you want to use it as a parameter in an URL leads to the generation of a different URL than you think. Smarty provides the <a href="http://www.smarty.net/docs/en/language.modifier.escape.tpl" rel="nofollow"><code>escape</code></a> variable modifier for this purpose.</p></li>
<li><p>You generate HTML and, because some characters are also special in HTML you have to properly encode them, otherwise the HTML you generate could be invalid and the browser could think the URL ends earlier than you intend. The <code>escape</code> modifier helps you here too.</p></li>
</ul>
<p>Putting all together, the best way is to build the URL into a separate Smarty <a href="http://www.smarty.net/docs/en/language.function.assign.tpl" rel="nofollow"><code>variable</code></a> then write it into the <code>href</code> attribute:</p>
<pre><code>{!--
* Generate the URL we want to send using WhatsApp
* and store it in the $url Smarty variable
* There is no encoding here
* --}
{capture assign=url}{strip}
http://{$smary.server.HTTP_HOST}{$smarty.server.REQUEST_URI}
{/strip}{/capture}
{!--
* The URL to invoke the WhatsApp app (and ask it to send $url as message) is:
* whatsapp://send?text={$url|escape:url}
* --}
{!--
* Generate correct HTML that contains the correct whatsapp URL
* that contains as parameter the URL generated in $url
* --}
<a class="whatsapp" href="whatsapp://send?text={$url|escape:url|escape:html}">Compartilhar</a>
</code></pre>
|
xtext scope code generation dependant on different file <p>I have two grammars <strong>A</strong> and <strong>B</strong> and two files <strong>a</strong> and <strong>b</strong> (using grammars <strong>A</strong> and <strong>B</strong> respectively). The file <strong>a</strong> specify variables names, <strong>b</strong> specify the filename of <strong>a</strong>.</p>
<p>In <strong>b</strong> using the the file <strong>a</strong> want to:</p>
<ul>
<li>reference variables defined in <strong>a</strong></li>
<li>during code generation of <strong>b</strong> I want to include the contents of the file created generated for <strong>a</strong>.</li>
</ul>
<p>How can this be done in xtext?</p>
<p><strong>Update 1</strong></p>
<p>Example grammar <strong>B</strong></p>
<pre><code>Model:
ref_model=RefModel
ref_vars+=[Vars]+
;
RefModel:
'reference' 'file' name=ID
;
</code></pre>
<p>Where <code>RefModel</code> define where the file <strong>a</strong> can be located and <code>Vars</code> are defined in <strong>a</strong>.</p>
| <p>In the past we used to use importURI for that, but you can do that through scoping on your own also.</p>
<p>If you for instance want to use the simple name of the file, you should make the name in B a reference to the root element of A.</p>
<pre><code>Model:
ref_model=RefModel
ref_vars+=[Vars]+
;
RefModel:
'reference' 'file' name=[ModelA]
;
</code></pre>
<p>Then you need to index the root element of A models using the simple file name of the resource URI.</p>
|
Function which applies a groupby <p>I have numerous dataframes I want to apply a function to.</p>
<p>My dataframes look like this:</p>
<pre><code>Year ID Pressure
1984 1 0.2
1985 2 0.5
1986 3 0.7
</code></pre>
<p>I am trying:</p>
<pre><code>def f(x):
return x.groupby(['ID']).Pressure.mean().to_frame().reset_index()
#apply the function to dataframes
df.apply(f)
df2.apply(f)
</code></pre>
<p>but this returns:</p>
<pre><code> KeyError: ('ID', u'occurred at index Year')
</code></pre>
<p>without a function I can do what I want like this:</p>
<pre><code>df=df.groupby(['ID']).Pressure.mean().to_frame().reset_index()
</code></pre>
| <p>apply is used when you want to <code>apply</code> a <code>function</code> to every values of a dataframe. since you just want to apply something to the entire df you should just do:</p>
<pre><code>f(df)
f(df2)
</code></pre>
|
Get value from textview in ListView Android <p>I'm following this guide to create a listview with textviews and eddittexts in it.
<a href="http://www.webplusandroid.com/creating-listview-with-edittext-and-textwatcher-in-android/" rel="nofollow">http://www.webplusandroid.com/creating-listview-with-edittext-and-textwatcher-in-android/</a>
When I try to get values from listview items, I get only textviews values. It seems impossible getting text from the edittext based on listview position.
I use <code>lv.getItemAtPosition(0).toString())</code> to retrieve values</p>
| <p>Following: <a href="http://stackoverflow.com/questions/257514/android-access-child-views-from-a-listview">Android: Access child views from a ListView</a></p>
<pre><code>int wantedChild = 1;
View wantedView = listview.getChildAt(wantedChild);
mEditText = (EditText) wantedView.findViewById(R.id.edittext);
Log.d("result",(mEditText.getText().toString()));
</code></pre>
|
socket.io GET /socket.io/?EIO=3&transport=polling&t=LV9VGzC" Error (404): "Not found" <pre><code>//backend code
var express = require("express");
var app = express();
var http = require('http');
var startServer=http.createServer(app);
var socketIO = require('socket.io').listen(startServer);
startServer.listen(8080, function () {
console.log('server running on',8080)
});
socketIO.on('connection', function (socket) {
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>connected')
var userSocketObject = {};
userSocketObject.socket_id = socket.id;
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
//index.html code angularjs
var socket = io.connect('http://127.0.0.1:8080');
socket.on('news', function(data){
console.log(data);
socket.emit('my other event', {my: 'data'});
});
</code></pre>
<p>I'm trying to connect but I'm getting an error in the browser:</p>
<pre><code>GET http://127.0.0.1:8080/socket.io/?EIO=3&transport=polling&t=LV9VGzC" Error (404): "Not found"
</code></pre>
| <p>i have resolved the problem , the problem was in directory path app.use(express.static(path.join('public')))</p>
|
Finding values that exist for every dictionary in a list <p>I have a list of lists that each have several dictionaries. The first list represents every coordinate involved in a triangulation. The second list represents a list of dictionaries associated with that grid coordinate. Each dictionary within the list represents every possible coordinate that is a certain Manhattan distance away from a line point that we are trying to triangulate, our target. Any coordinate that exists within every triangulation list represent the overlapping points from these positions and thus the potential location of our target.</p>
<p>Anyway, I gave some background to hopefully add some understanding. I know it probably comes off confusing, but I'll include my data structure to assist in visualizing what is going on. I've tried looping through these and haven't quite found a way to do this efficiently yet. </p>
<p>Does anyone know of some Python magic to generate a list of the coordinates that exist in every group of coordinates? </p>
<p>So in the example below we are starting with 3 different groups of coordinates. I need to generate a list of any x,y pairs that exists in all 3 groups of coordinates.</p>
<p>Example:</p>
<pre><code>[
[
{'x': 1, 'y': 0},
{'x': -1, 'y': 0},
{'x': 0, 'y': 1},
{'x': 0, 'y': -1}
],
[
{'x': 2, 'y': 0},
{'x': -2, 'y': 0},
{'x': 0, 'y': 2},
{'x': 0, 'y': -2},
{'x': 1, 'y': 1},
{'x': -1, 'y': -1},
{'x': -1, 'y': 1},
{'x': 1, 'y': -1}
],
[
{'x': 3, 'y': 0},
{'x': -3, 'y': 0},
{'x': 0, 'y': 3},
{'x': 0, 'y': -3},
{'x': 2, 'y': 1},
{'x': -2, 'y': -1},
{'x': -1, 'y': 2},
{'x': 1, 'y': -2},
{'x': 1, 'y': 2},
{'x': -1, 'y': -2},
{'x': -2, 'y': 1},
{'x': 2, 'y': -1}
]
]
</code></pre>
| <p>There is no magic. You just need to be a bit more careful with your data structures. You are putting coordinates in a dict which are not hashable. So you cannot add them to a set. You need to use tuples. So your data structure should look like this:</p>
<pre><code>my_list = [
set([
(1, 0),
(-1, 0),
(0, 1),
(0, -1)
]),
set([
(1, 0),
(-2, 0),
(0, 2),
(0, -2),
(1, 1),
(-1, -1),
(-1, 1),
(1, -1)
]),
set([
(1, 0),
(-3, 0),
(0, 3),
(0, -3),
(2, 1),
(-2, -1),
(-1, 2),
(1, -2),
(1, 2),
(-1, -2),
(-2, 1),
(2, -1)
])
]
common = my_list[0]
for s2 in my_list[1:]:
common = common & s2
print common
</code></pre>
|
Need help referencing a pointer from a header file <p>I've asked a question similar to this and received help and figured it out, but this seems to be a bit different. I'm trying to reference a pointer from a struct in a header file but I keep getting a "expected identifier or ')' before '->' token" error.</p>
<p>what I'm trying to get to the digits pointer:</p>
<pre><code>typedef struct HugeInteger
{
int *digits;
int length;
} HugeInteger;
</code></pre>
<p>by using:</p>
<pre><code>HugeInteger->digits;
</code></pre>
<p>but I keep getting the error. I've tried it a few different ways but I keep getting the same error.</p>
<p>Thank you in advance for any advice you can give!.</p>
| <p>In</p>
<pre><code>typedef struct HugeInteger
{
int *digits;
int length;
} HugeInteger;
</code></pre>
<p>the <code>typedef</code> makes <code>HugeInteger</code> an alias for <code>struct HugeInteger</code> (this is totally unnecessary on C++. Defining <code>struct HugeInteger</code> implies <code>HugeInteger</code> is valid) so <code>HugeInteger->digits;</code> isn't dereferencing and accessing a member of a variable of a type, it is trying to dereference and access a member of a type. No variable.</p>
<p>Without the <code>typedef</code> <code>HugeInteger</code> would be a variable, so you'd think </p>
<pre><code>struct HugeInteger
{
int *digits;
int length;
} HugeInteger;
</code></pre>
<p>Will solve the problem, right? Well besides the human-side problems that will stem from having a variable of the same name as the type, the variable <code>HugeInteger</code> isn't a pointer so the <code>HugeInteger->digits;</code> syntax is still invalid.</p>
<p>Approaching this from the other side, and keeping the <code>typedef</code>, OP needs something like</p>
<pre><code>HugeInteger * heeeeyuge;
</code></pre>
<p>and then to assign storage to <code>heeeeyuge</code> by pointing it at a preexisting allocation, <code>malloc</code>ing a block of storage (in C), or <code>new</code>ing a block of storage (in C++)</p>
<p>What OP will most likely find is that having a pointer is not what they want. and </p>
<pre><code>HugeInteger.digits
</code></pre>
<p>or</p>
<pre><code>HugeInteger heeeeyuge;
heeeeyuge.digits
</code></pre>
<p>will suffice.</p>
<p>If the target is C++, may I suggest </p>
<pre><code>struct HugeInteger
{
std::vector<int> digits;
};
</code></pre>
<p>instead? Automatic memory management is the bomb.</p>
|
Adding data to existing h5py file along new axis using h5py <p>I have some sample code that generates a 3d Numpy array -- I am then saving this data into a h5py file using h5 file. How can I then "append" the second dataset along the 4th dimension? Or, how can I write another 3d dataset along the 4th dimension (or new axis) of an existing <code>.h5</code> file? I have read documentation that I could find, and none of the examples seem to address this. My code is shown below:</p>
<pre><code>import h5py
import numpy as np
dataset1 = np.random.rand(240,240,250);
dataset2 = np.random.rand(240,240,250);
with h5py.File('data.h5', 'w') as hf:
dset = hf.create_dataset('dataset_1', data=dataset1)
</code></pre>
| <p>Using <a href="http://docs.h5py.org/en/latest/high/dataset.html" rel="nofollow">http://docs.h5py.org/en/latest/high/dataset.html</a> I experimented a bit:</p>
<pre><code>In [504]: import h5py
In [505]: f=h5py.File('data.h5','w')
In [506]: data=np.ones((3,5))
</code></pre>
<p>Make an ordinary <code>dataset</code>:</p>
<pre><code>In [509]: dset=f.create_dataset('dset', data=data)
In [510]: dset.shape
Out[510]: (3, 5)
In [511]: dset.maxshape
Out[511]: (3, 5)
</code></pre>
<p>Help for <code>resize</code>:</p>
<pre><code>In [512]: dset.resize?
Signature: dset.resize(size, axis=None)
Docstring:
Resize the dataset, or the specified axis.
The dataset must be stored in chunked format; it can be resized up to
the "maximum shape" (keyword maxshape) specified at creation time.
The rank of the dataset cannot be changed.
</code></pre>
<p>Since I didn't specify <code>maxshape</code> it doesn't look like I can change or add to this dataset.</p>
<pre><code>In [513]: dset1=f.create_dataset('dset1', data=data, maxshape=(2,10,10))
...
ValueError: "maxshape" must have same rank as dataset shape
</code></pre>
<p>So I can't define a 3d 'space' and put a 2d array in it - at least not this way.</p>
<p>But I can add a dimension (rank) to <code>data</code>:</p>
<pre><code>In [514]: dset1=f.create_dataset('dset1', data=data[None,...], maxshape=(2,10,10))
In [515]: dset1
Out[515]: <HDF5 dataset "dset1": shape (1, 3, 5), type "<f8">
</code></pre>
<p>Now I can resize the dataset - in 1 or more dimensions, up to the defined max.</p>
<pre><code>In [517]: dset1.resize((2,3,10))
In [518]: dset1
Out[518]: <HDF5 dataset "dset1": shape (2, 3, 10), type "<f8">
In [519]: dset1[:]
Out[519]:
array([[[ 1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],
[ 1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],
[ 1., 1., 1., 1., 1., 0., 0., 0., 0., 0.]],
[[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]])
</code></pre>
<p>The original <code>data</code> occupies a corner of the expanded dataset</p>
<p>Now fill in some zeros:</p>
<pre><code>In [521]: dset1[1,:,:]=10
In [523]: dset1[0,:,5:]=2
In [524]: dset1[:]
Out[524]:
array([[[ 1., 1., 1., 1., 1., 2., 2., 2., 2., 2.],
[ 1., 1., 1., 1., 1., 2., 2., 2., 2., 2.],
[ 1., 1., 1., 1., 1., 2., 2., 2., 2., 2.]],
[[ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]]])
</code></pre>
<p>So yes, you can put both of your <code>dataset</code> in one <code>h5</code> dataset, provided you specified a large enough <code>maxshape</code> to start with, e.g. (2,240,240,250) or (240,240,500) or (240,240,250,2) etc.</p>
<p>Or for unlimited resizing <code>maxshape=(None, 240, 240, 250))</code>.</p>
<p>Looks like the main constraint is you can't added a dimension after creation.</p>
<p>Another approach is to concatenate the data before storing, e.g.</p>
<pre><code>dataset12 = np.stack((dataset1, dataset2), axis=0)
</code></pre>
|
digits to words from sys.stdin <p>I'm trying to convert digits to words from std input (txt file).
If the input is for example : 1234, i want the output to be one two three four, for the next line in the text file i want the output to be on a new line in the shell/terminal:
1234 one two three four
56 five six
The problem is that i can't get it to output on the same line.
Code so far :</p>
<pre><code>#!/usr/bin/python3
import sys
import math
def main():
number_list = ["zero","one","two","three","four","five","six","seven","eight","nine"]
for line in sys.stdin:
number = line.split()
for i in number:
number_string = "".join(i)
number2 = int(number_string)
print(number_list[number2])
main()
</code></pre>
| <p>Put the words in a list, join them, and print the line.</p>
<pre><code>#!/usr/bin/python3
import sys
import math
def main():
number_list = ["zero","one","two","three","four","five","six","seven","eight","nine"]
for line in sys.stdin:
digits = list(line.strip())
words = [number_list[int(digit)] for digit in digits]
words_line = ' '.join(words)
print(words_line)
main()
</code></pre>
|
Save and Load data in Python 3 <p>I have to create a team roster that saves and loads the data. I have it to the point where everything else works but saving and loading.</p>
<pre><code>memberList = []
#get first menu selection from user and store in control value variable
def __init__(self, name, phone, number):
self.__name = name
self.__phone = phone
self.__number = number
def setName(self, name):
self.__name = name
def setPhone(self, phone):
self.__phone = phone
def setnumber(self, number):
self.__number = number
def getName(self):
return self.__name
def getPhone(self):
return self.__phone
def getNumber(self):
return self.__number
def displayData(self):
print("")
print("Player's Information")
print("-------------------")
print("Player's Name:", getName)
print("Player's Telephone number:", getPhone)
print("Player's Jersey number:", getNumber)
def displayMenu():
print("==========Main Menu==========")
print("1. Display Team Roster")
print("2. Add Member")
print("3. Remove Member")
print("4. Edit Member")
print("9. Exit Program")
print()
return int(input("Selection>"))
menuSelection = displayMenu()
def printMembers(memberList):
print("Current members: ")
if len(memberList) == 0:
print("No current members in memory.")
else:
x = 1
while x < len(memberList):
print(memberList[x],)
x = x + 1
def addPlayer(memberList): # players as an argument
newName = input("Add a player's Name: ")
newPhone = input("Telephone number: ")
newNumber = input("Jersey number: ")
memberList.append(newName)
return memberList
def removePlayer(memberList):
removeName = input("What name would you like to remove? ", )
# Don't redefine it!
if removeName in memberList:
del memberList[removeName]
else:
print("Sorry", removeName, "was not found!")
return memberList
def editPlayer(memberList):
oldName = input("What name would you like to change? ", )
if oldName in memberList:
newName = input("What is the new name? ")
print("***", oldName, "has been changed to", newName)
else:
print("***Sorry", oldName, "was not found!")
return memberList
def saveData(memberList):
filename=input("Filename to save: ", )
print("saving data...")
outfile=open(filename, "wt")
filename= '/Users\nativ\ Documents'
for x in memberList:
name = memberList[x].getName()
phone = memberList[x].getPhone()
number = memberList[x].getNumber()
outfile.write("name","age", 'number')
print("Data Saved")
outfile.close()
def loadData():
filename = input("Filename to load: ")
inFile = open(filename, "rt")
def exitProgram(memberList):
print("Exiting Program...")
while menuSelection != 9:
if menuSelection == 1:
printMembers = printMembers(memberList)
menuSelection = displayMenu()
elif menuSelection == 2:
memberList = addPlayer(memberList)
menuSelection = displayMenu()
elif menuSelection == 3:
memberList = removePlayer(memberList)
menuSelection = displayMenu()
elif menuSelection == 4:
memberList = editPlayer(memberList)
menuSelection = displayMenu()
elif menuSelection == 5:
memberList = saveData(memberList)
menuSelection = displayMenu()
elif menuSelection == 6:
memberList = loadData()
menuSelection = displayMenu()
print('Welcome to the Team Manager')
displayMenu()
</code></pre>
<p>This is the error code that I am getting</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/nativ/PycharmProjects/Week2/Week 5.py", line 98, in <module>
memberList = saveData(memberList)
File "C:/Users/nativ/PycharmProjects/Week2/Week 5.py", line 73, in saveData
name = memberList[x].getName()
TypeError: list indices must be integers or slices, not str
</code></pre>
| <p>Try <code>name = memberList[int(x)].getName()</code>. When it reads the data from a file it reads a string, and in order to put that into a list you need to make it an integer.</p>
|
Convert mapply output to dataframe variable <p>I have a data frame like this:</p>
<pre><code>df <- data.frame(x=c(7,5,4),y=c(100,100,100),w=c(170,170,170),z=c(132,720,1256))
</code></pre>
<p>I create a new column using mapply:</p>
<pre><code>set.seed(123)
library(truncnorm)
df$res <- mapply(rtruncnorm,df$x,df$y,df$w,df$z,25)
</code></pre>
<p>So, I got:</p>
<pre><code>> df
#x y w z res
#1 7 100 170 132 117.9881, 126.2456, 133.7627, 135.2322, 143.5229, 100.3735, 114.8287
#2 5 100 170 720 168.8581, 169.4955, 169.6461, 169.8998, 169.0343
#3 4 100 170 1256 169.7245, 167.6744, 169.7025, 169.4441
#dput(df)
df <- structure(list(x = c(7, 5, 4), y = c(100, 100, 100), w = c(170,
170, 170), z = c(132, 720, 1256), res = list(c(117.988108836195,
126.245562762918, 133.762709785614, 135.232193379024, 143.52290514973,
100.373469134837, 114.828678702662), c(168.858147661715, 169.495493758985,
169.646123183828, 169.899849943838, 169.034333943479), c(169.724470294466,
167.674371713068, 169.70250974042, 169.444134892323))), .Names = c("x",
"y", "w", "z", "res"), row.names = c(NA, -3L), class = "data.frame")
</code></pre>
<p>But what I really need is repeat each row of df dataframe according to the <code>df$res</code> result as follows:</p>
<pre><code>> df2
# x y w z res
#1 7 100 170 132 117.9881
#2 7 100 170 132 126.2456
#3 7 100 170 132 133.7627
#4 7 100 170 132 135.2322
#5 7 100 170 132 143.5229
#6 7 100 170 132 100.3735
#7 7 100 170 132 114.8287
#8 5 100 170 720 168.8581
#9 5 100 170 720 169.4955
#10 5 100 170 720 169.6461
#11 5 100 170 720 169.8998
#12 5 100 170 720 169.0343
#13 4 100 170 1256 169.7245
#14 4 100 170 1256 167.6744
#15 4 100 170 1256 169.7025
#16 4 100 170 1256 169.4441
</code></pre>
<p>How, do I achieve this efficiently? I need to apply this to a big dataframe</p>
| <pre><code>df <- data.frame(x=c(7,5,4),y=c(100,100,100),w=c(170,170,170),z=c(132,720,1256))
set.seed(123)
l <- mapply(rtruncnorm,df$x,df$y,df$w,df$z,25)
cbind.data.frame(df[rep(seq_along(l), lengths(l)),],
res = unlist(l))
# x y w z res
# 1 7 100 170 132 117.9881
# 1.1 7 100 170 132 126.2456
# 1.2 7 100 170 132 133.7627
# 1.3 7 100 170 132 135.2322
# 1.4 7 100 170 132 143.5229
# 1.5 7 100 170 132 100.3735
# 1.6 7 100 170 132 114.8287
# 2 5 100 170 720 168.8581
# 2.1 5 100 170 720 169.4955
# 2.2 5 100 170 720 169.6461
# 2.3 5 100 170 720 169.8998
# 2.4 5 100 170 720 169.0343
# 3 4 100 170 1256 169.7245
# 3.1 4 100 170 1256 167.6744
# 3.2 4 100 170 1256 169.7025
# 3.3 4 100 170 1256 169.4441
</code></pre>
|
How to make a dynamic grid in Python <p>I am building an X's and O's (tic tac toe) application where the user can decide whether the grid is between 5X5 and 10X10, how do I write the code so that the grid is dynamic? </p>
<p>At the moment this is all I have to make a grid of one size:</p>
<pre><code> grid = [[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0]]
</code></pre>
| <p>Code:</p>
<pre><code>#defining size
x = y = 5
#create empty list to hold rows
grid = []
#for each row defined by Y, this loop will append a list containing X occurrences of "0"
for row in range(y):
grid.append(list("0"*x))
print grid
</code></pre>
<p>Output:</p>
<pre><code>[['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0']]
</code></pre>
|
Neo4j - return only one node that has multiple relations <p>I'm having a small issue finding out how to return one node, that has multiple outgoing relations.</p>
<p>So what I want is to display only node, even if it has more than one relation; this is my query:</p>
<pre><code>MATCH total=(n:Employee)-[r:WorkedOn]->(p:Project)
RETURN toFloat(p.total_efficiency) / toFloat(count(p)) as score , n.first_name as name, n.last_name as surname, r.role as role, n.start_date_of_work as startDate, n.experience as experience,
n.email as email, n.age as age, collect(p.name) as projects ORDER BY score DESC LIMIT {l}
</code></pre>
<p>but this returns a table like this:</p>
<p><a href="https://i.stack.imgur.com/kBodO.png" rel="nofollow"><img src="https://i.stack.imgur.com/kBodO.png" alt="the result generated with Spring boot"></a></p>
<p>How do I solve the double 'Jari Van Melckebeke' records? I only want one.<br>
I could also remove the 'role' property, but I need the Project object anyway to calculate the score...</p>
<p>Thanks in advance,
Jari Van Melckebeke</p>
| <p>You have two options to collapse this into one row. Either, as you suggested, removing role from your return, or returning <code>COLLECT(r.role) as roles</code>.</p>
|
How to use ResolveComponentFactory() but with a string as a key <p>what I'm trying to do:</p>
<ul>
<li>Use something similar to the "resolveComponentFactory()", but with a 'string' identifier to get Component Factories. </li>
<li>Once obtained, start leverage the "createComponent(Factory)" method.</li>
</ul>
<p>Plnkr Example -> <a href="https://plnkr.co/edit/OjDaqijUTVIbzMX4JZ5c?p=preview" rel="nofollow">enter link description here</a></p>
<p>In the example, you will see the "AddItem" method</p>
<pre><code>addItem(componentName:string):void{
let compFactory: ComponentFactory;
switch(componentName){
case "image":
compFactory = this.compFactoryResolver.resolveComponentFactory(PictureBoxWidget);
break;
case "text":
compFactory = this.compFactoryResolver.resolveComponentFactory(TextBoxWidget);
break;
}
//How can I resolve a component based on string
//so I don't need to hard cost list of possible options
this.container.createComponent(compFactory);
</code></pre>
<p>}</p>
<p>The "compFactoryResolver:ComponentFactoryResolver" is injected in the contructor.</p>
<p>As you will note, having to hard code every permutation in a switch statement is less than ideal.</p>
<p>when logging the ComponentFactoryResolver to the console, I've observed that it contains a Map with the various factories. </p>
<pre><code>CodegenComponentFactoryResolver {_parent: AppModuleInjector, _factories: Map}
</code></pre>
<p>However, this map is a private and can't be easily accessed (from what I can tell).</p>
<p>Is there a better solution then somehow rolling my own class to get access to this factory list? </p>
<p>I've seen a lot of messages about people trying to create dynamic components. However, these are often about creating components at run time. the components in question here are already pre-defined, I am stuck trying to access factories using a string as a key.</p>
<p>Any suggestions or advice are much appreciated.</p>
<p>Thank you kindly.</p>
| <p>It's either defining a map of available components,</p>
<pre><code>const compMap = {
text: PictureBoxWidget,
image: TextBoxWidget
};
</code></pre>
<p>Or defining identifiers as static class property that will be used to generate a map,</p>
<pre><code>const compMap = [PictureBoxWidget, TextBoxWidget]
.map(widget => [widget.id, widget])
.reduce((widgets, [id, widget]) => Object.assign(widgets, { [id]: widget }), {});
</code></pre>
<p>The map is then used like</p>
<pre><code>let compFactory: ComponentFactory;
if (componentName in compMap) {
compFactory = this.compFactoryResolver.resolveComponentFactory(compMap[componentName]);
} else {
throw new Error(`Unknown ${componentName} component`);
}
</code></pre>
<p>There's no way how component classes can be magically identified as strings, because they aren't resolved to strings in Angular 2 DI (something that was changed since Angular 1, where all DI units were annotated as strings).</p>
|
Getting error Resource violated directive 'script-src ms-appx: 'unsafe-eval'' in Host Defined Policy: inline script. Resource will be blocked <p>I am trying to use Visual studio to make a universal windows app. When I try to run the following code:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>testProject</title>
<link href="css/default.css" rel="stylesheet" />
</head>
<body>
<div>Content goes here!</div><script src="js/main.js"></script>
<form name="myForm">
<input type="radio" name="myRadio" value="yes"/> Yes <br />
<input type="radio" name="myRadio" value="No"/> No <br />
<input type="button" name="submit"value="submit" onsubmit="return validateForm" />
</form>
</body>
</html>
</code></pre>
<p>In JavaScript main file:</p>
<pre><code>function ValiditeForm(){
document.writeln("Hello World");
}
</code></pre>
<p>When I attempt to run I get the following warning:</p>
<p>CSP14312: Resource violated directive 'script-src ms-appx: 'unsafe-eval'' in Host Defined Policy: inline script. Resource will be blocked.</p>
<p>All I am simply trying to do is write HTML code using the visual studio universal app that upon a user clicking a radio button in a HTML form, that it will be passed to a function in JavaScript and will print out a value.</p>
| <p>The error says it's all.</p>
<p>You aren't allowed to put <code><script src=...</code>out of head. </p>
<p>This should be the case when using CSP Directives <a href="https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives</a></p>
<p>You can turn off them in IIS in the <code>HTTP Response heathers</code> option </p>
<p><a href="http://i.stack.imgur.com/jp7Qs.png" rel="nofollow"><img src="http://i.stack.imgur.com/jp7Qs.png" alt="inetmgr"></a></p>
<p>And deleting <code>unsafe-eval</code> from the config line:</p>
<p><a href="http://i.stack.imgur.com/tkIKX.png" rel="nofollow"><img src="http://i.stack.imgur.com/tkIKX.png" alt="unsafe-eval"></a></p>
|
'SelectedIndex' : Undeclared identifier in C++ <p>I'm writing a simple program that references the state of
SelectedIndex which at any given point can be a number 0 - 9</p>
<p>SelectedIndex is controlled by a dropdownlist.</p>
<p>When I try and reference the state of SelectedIndex:</p>
<pre><code>if (SelectedIndex == 0)
{
textBox1->Text = "C Egyptian";
}
</code></pre>
<p>I'm getting an "undeclared identifier" error upon compiling.</p>
<p>I just want to be able to reference the state SelectedIndex for my conditional.</p>
<p>Any ideas?</p>
| <p>Nvm Sorry for the n00b question... I'm very new to C++ but I actually figured it out myself in VS just on a guess.</p>
<p>Problem was I should have been using</p>
<pre><code>if (comboBox1->SelectedIndex == 0)
{
textBox1->Text = "C Egyptian";
}
</code></pre>
<p>instead of</p>
<pre><code>if (SelectedIndex == 0)
{
textBox1->Text = "C Egyptian";
}
</code></pre>
<p>have a good one</p>
|
Casting an array of C structs to a numpy array <p>A function I'm calling from a shared library returns a structure called info similar to this:</p>
<pre><code>typedef struct cmplx {
double real;
double imag;
} cmplx;
typedef struct info{
char *name;
int arr_len;
double *real_data
cmplx *cmplx_data;
} info;
</code></pre>
<p>One of the fields of the structure is an array of doubles while the other is an array of complex numbers. How do I convert the array of complex numbers to a numpy array? For doubles I have the following:</p>
<pre><code>from ctypes import *
import numpy as np
class cmplx(Structure):
_fields_ = [("real", c_double),
("imag", c_double)]
class info(Structure):
_fields_ = [("name", c_char_p),
("arr_len", c_int),
("real_data", POINTER(c_double)),
("cmplx_data", POINTER(cmplx))]
c_func.restype = info
ret_val = c_func()
data = np.ctypeslib.as_array(ret_val.contents.real_data, shape=(info.contents.arr_len,))
</code></pre>
<p>Is there a numpy one liner for complex numbers? I can do this using loops.</p>
| <p>Define your field as double and make a complex view with numpy:</p>
<pre><code>class info(Structure):
_fields_ = [("name", c_char_p),
("arr_len", c_int),
("real_data", POINTER(c_double)),
("cmplx_data", POINTER(c_double))]
c_func.restype = info
ret_val = c_func()
data = np.ctypeslib.as_array(ret_val.contents.real_data, shape=(info.contents.arr_len,))
complex_data = np.ctypeslib.as_array(ret_val.contents.cmplx_data, shape=(info.contents.arr_len,2)).view('complex128')
</code></pre>
|
How to reference another column in another table when writing a trigger? <p>I have a table <code>EmpSalary</code> which has a column <code>salaryPaid</code>, the current salary of the employee and a table <code>Emp</code> which has a column <code>baseSalary</code>, the lowest salary available for that employee's job. I want to write a trigger for the <code>EmpSalary</code> table that does some calculation to ensure the employee is being paid within a certain percent range(not 70% more than <code>baseSalary</code> of that employee's job).
<br>
<br>
I have the calculations worked out on paper but I'm not sure how to reference the <code>Emp</code> table when I'm writing a trigger on the <code>EmpSalary</code> table?</p>
<p><code>CREATE TRIGGER Check_Salary
BEFORE INSERT OR UPDATE ON EmpSalary
FOR EACH ROW
DECLARE
v_salary;
v_baseSalary;
...
BEGIN
v_salary := old.salaryPaid
v_baseSalary := Emp.baseSalary
...
END;
/</code></p>
<p>any insight would be great! Trying to study for a big exam.</p>
| <p>You can perform a SELECT in a trigger, as long as the table you're SELECTing data from isn't the one on which the trigger is defined. In this case you can SELECT the data from EMP:</p>
<pre><code>CREATE OR REPLACE TRIGGER Check_Salary
BEFORE INSERT OR UPDATE ON EmpSalary
FOR EACH ROW
DECLARE
v_salary NUMBER;
v_baseSalary NUMBER;
...
BEGIN
v_salary := old.salaryPaid;
SELECT BASESALARY
INTO v_baseSalary
FROM EMP
WHERE EMP.some_key_column = :old.some_key_column;
...
END;
</code></pre>
<p>Best of luck.</p>
|
http.ListenAndServe only works for localhost? <p>I've been successfully making use of </p>
<pre><code>http.ListenAndServe(":80", mux)
</code></pre>
<p>to host my web service in Go. It only appears to work with localhost however.</p>
<pre><code>http.ListenAndServe("192.168.1.83:80", mux)
</code></pre>
<p>This works for specific connections on this address but is there a way to make it work for any ip address on the server?</p>
<p><strong>Edit:</strong></p>
<p>I've checked it with a different port (8080 in this case) and then using ":8080" works as documented. There appears to be something special about port 80 even when testing on the same machine that means it only actually listens on localhost.</p>
<p>For the avoidance of doubt I'm using Windows and all testing is done on the same physical machine. I've also checked running with admin privileges and it makes no difference.</p>
| <p><code>http.ListenAndServe(":80", mux)</code> is the correct address. <a href="https://golang.org/pkg/net/http/" rel="nofollow"><code>net/http</code></a> uses the <a href="https://golang.org/pkg/net/" rel="nofollow"><code>net</code></a> package. Quoting from <a href="https://golang.org/pkg/net/#Listen" rel="nofollow"><code>net.Listen()</code></a>:</p>
<blockquote>
<p>If host is omitted, as in ":8080", <strong>Listen listens on all available interfaces</strong> instead of just the interface with the given host address. See Dial for more details about address syntax.</p>
</blockquote>
<p>Know that port 80 is restricted or might be blocked by firewalls on many systems. On unix systems ports under 1024 usually require special permissions. Test the 8080 port for example, because that is not special in this way. </p>
|
Palindrome number in java doesn't seem to make sense <p>I'm doing some exercise programs in Java and came to this palindrome number exercise which tells if the number is palindrome, I'm getting the correct output but I'm trying to explain to myself how the program is working line by line, upon reaching a specific line I noticed that that part doesn't seem to add up, here is the code:</p>
<pre><code>public class Palindrome {
public static void main(String[] args) {
int p = 252;
if(isPalindrome(p)) {
System.out.println("Palindrome");
} else {
System.out.println("Not palindrome");
}
}
public static boolean isPalindrome(int x) {
int num = x;
int rev = 0;
while (num != 0) {
int rmd = num % 10;//the remainder of 252 is 2
rev = rev * 10 + rmd;//rev which is 0 multiplied by 10 is 0 + 2 is 2
num = num / 10;
}
if (x == rev) {//x = 252 and rev = 2
return true;
}
return false;
}
}
</code></pre>
<p>in the part: <code>if(x == rev)</code> how can it be true when 252 is not equal to 2? thanks guys..</p>
| <p>You have to look what happens during the loop as it goes through its iterations.</p>
<p>For simple programs, such as this one, a paper-and-pencil approach works fine. For more complex programs adding "debug prints" help you understand what is going on:</p>
<pre><code>int iterationCount = 0;
while (num != 0) {
System.out.println("Before iteration="+iterationCount+" num="+num+" rev="+rev);
int rmd = num % 10;//the remainder of 252 is 2
rev = rev * 10 + rmd;//rev which is 0 multiplied by 10 is 0 + 2 is 2
num = num / 10;
System.out.println("After iteration="+iterationCount+" num="+num+" rev="+rev);
iterationCount++;
}
</code></pre>
<p>This <a href="http://ideone.com/fVmyHn" rel="nofollow">produces</a> the following output:</p>
<pre><code>Before iteration=0 num=252 rev=0
After iteration=0 num=25 rev=2
Before iteration=1 num=25 rev=2
After iteration=1 num=2 rev=25
Before iteration=2 num=2 rev=25
After iteration=2 num=0 rev=252
Palindrome
</code></pre>
<p>Note how <code>num</code> decreases down to zero, while <code>rev</code> grows to <code>252</code> with each iteration.</p>
|
Haskell: Random Coin Instance <p>I have defined a <code>Coin</code> data type:</p>
<pre><code>data Coin = H | T
deriving (Bounded, Eq, Enum, Ord, Show)
</code></pre>
<p>I now have to write a Random Coin instance, given the following framework:</p>
<pre><code>instance Random Coin where
randomR (l, h) g = undefined
random = undefined
</code></pre>
<p>Obviously, this random instance should return either H or T. I'm beginning to start understanding how Monads work, however, I'm confused about the initial random generator. I get that a random generator returns a <code>(a, gen)</code>, but where do we get the initial generator to create a first random Coin? I currently have the following:</p>
<pre><code>instance Random Coin where
randomR (l, h) g = case randomR(l, h) g of
(c, g') -> (c, g')
random = getStdRandom(randomR(minBound :: Coin, maxBound :: Coin))
</code></pre>
<p>I'm especially confused about the <code>random</code> function, since particular expression seems to return type IO Coin. Any help to enlighten me is much appreciated!</p>
| <p>The functions you are defining have types</p>
<pre><code>randomR :: RandomGen g => (Coin, Coin) -> StdGen -> (Coin, StdGen)
random :: RandomGen g => StdGen -> (Coin, StdGen)
</code></pre>
<p>In other words, you're already given a random generator -- the second argument of randomR and the first of random. Any attempt to get a system random generator will cause a type error, because suddenly you've added IO into the mix, and that occurs nowhere in these types.</p>
<p>Usually, random instances translate one of the Integer-based functions into the specific types needed. For instance, we could use</p>
<pre><code> randomR :: (RandomGen g) => (Integer, Integer) -> g -> (Integer, g)
</code></pre>
<p>to produce a number in the range (0,1) and translate 0 into <code>H</code> and 1 into <code>T</code>.</p>
<pre><code>instance Random Coin where
randomR (low,high) generator =
case randomR (toInt low, toInt high) generator of
(i,g) -> (toCoin i, g)
where
toInt :: Coin -> Integer
toInt H = 0
toInt T = 1
toCoin 0 = H
toCoin 1 = T
</code></pre>
<p>I'll leave <code>random</code> for you to define.</p>
<p>By the way, you might realize that this is basically the same instance that <code>Bool</code> must have, so a sensible way to solve your problem would also have been to check the <a href="https://hackage.haskell.org/package/random-1.1/docs/src/System-Random.html" rel="nofollow">source code for the "random" package</a> and search for "instance Random Bool".</p>
<p>Afterwards, you could use it with any random generator, like so:</p>
<pre><code>> let gen = mkStdGen 1 in take 10 $ randomRs (H,T) gen
[T,T,T,H,H,T,H,H,H,T]
</code></pre>
|
Update or add value to list <p>How would you either update <code>inventory</code>(based on name) or add if name not found.</p>
<pre><code>var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
</code></pre>
<p>For example, the following will update the inventory:</p>
<pre><code>const fruit = {name: 'bananas', quantity: 1}
inventory = inventory.map(f => f.name===fruit.name ? fruit : f);
</code></pre>
<p>and this could be used to add to the inventory:</p>
<pre><code>const fruit = {name: 'oranges', quantity: 2}
if (!inventory.find(f => f.name===fruit.name)) inventory.push(fruit)
</code></pre>
<p>but I'm looking for a solution which can do both and which preferably uses arrow functions rather than indexes - if possible.</p>
| <p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" rel="nofollow"><code>findIndex</code></a>:</p>
<pre><code>var idx = inventory.findIndex(f => f.name === fruit.name);
inventory[idx < 0 ? inventory.length : idx] = fruit;
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
var fruit = {name: 'bananas', quantity: 1}
var idx = inventory.findIndex(f => f.name === fruit.name);
inventory[idx < 0 ? inventory.length : idx] = fruit;
var fruit = {name: 'oranges', quantity: 2}
var idx = inventory.findIndex(f => f.name === fruit.name);
inventory[idx < 0 ? inventory.length : idx] = fruit;
console.log(inventory);</code></pre>
</div>
</div>
</p>
<p>In case you want to merge two arrays of objects (instead of a single object to an array), then this approach would be quadratic. You should see <a href="http://stackoverflow.com/a/30335130/1529630">JavaScript merging objects by id</a> instead.</p>
|
How can I change the memory address of char*? <p>I am dealing with a problem that I cannot get abs_path and query arrays filled with a data I am passing to them inside of the function parse. Inside this function logic seems to be correct, I have debugged it and both of the arrays are filled with a correct data. I know that I am not passing a pointer to arrays (char**) in the parameters due to a condition that function's parameters cannot be changed. Any other advice on solving this problem?</p>
<pre><code>#define LimitRequestLine 8190
char abs_path[LimitRequestLine + 1];
char query[LimitRequestLine + 1];
bool parse(const char* line, char* abs_path, char* query)
{
char* method = "GET ";
char* valid_http = "HTTP/1.1";
int index, method_size;
char abs_path_line[LimitRequestLine + 1];
char query_line[LimitRequestLine + 1];
int abs_path_index;
if(strstr(line, "HTTP/")!=NULL && strstr(line, valid_http) == NULL) {
error(505);
return false;
}
//make sure that our method is GET
for(index = 0, method_size = strlen(method); index<method_size; index++) {
if(line[index] != method[index]) {
error(405);
return false;
}
}
//check if request-target starts with '/'
if(line[index]!='/') {
error(501);
return false;
}
for(abs_path_index = 0; index < strlen(line); index++) {
//if there is a quotation mark, then we have a query in request-target
if(line[index] == '?') {
index++;
int query_index;
for(query_index = 0; line[index]!=' '; index++) {
//check if there is quote mark in query
if(line[index] == '"') {
error(400);
return false;
}
query_line[query_index] = line[index];
query_index++;
}
query_line[query_index] = '\0';
}
//assuming that we have not found any '?' mark for query.
if(strstr(line, "?") == NULL) {
query_line[0] = '\0';
}
if(line[index] == ' ') {
int temp = index;
index++;
/*After the space there should be a valid http, if it is not found,
then there is/are spaces in our request-line which is incorrect*/
for(int i=0; i<strlen(valid_http); i++) {
if(line[index] != valid_http[i]) {
error(400);
return false;
}
index++;
}
index = temp;
break;
}
//check if there is quote mark in abs_path
if(line[index] == '"') {
error(400);
return false;
}
abs_path_line[abs_path_index] += line[index];
abs_path_index++;
}
abs_path_line[abs_path_index] += '\0';
abs_path = abs_path_line;
abs_path += '\0';
query = query_line;
printf("abs path is %s\n", abs_path);
printf("query is %s\n", query);
return true;
}
</code></pre>
| <p>The problem is this:</p>
<pre><code>query = query_line;
</code></pre>
<p><code>char *query</code> means you are passed a pointer. It's just a number like any other number. Think of it this way.</p>
<pre><code>void set_number(int number) {
number = 6;
}
</code></pre>
<p>Do you expect this to do anything? Nope. Same thing with <code>query = query_line</code>.</p>
<p>Instead, <code>query</code> points at a hunk of memory. You need to copy <code>query_line</code> into the memory that <code>query</code> points at and hope there's enough allocated space.</p>
<pre><code>strncpy(query, query_line, LimitRequestLine);
</code></pre>
<hr>
<p>Functions that require the caller to allocate memory are memory problems waiting to happen. Instead of fixing this one I would recommend...</p>
<ol>
<li>Writing a new function with a better signature, maybe returning a struct.</li>
<li>Implement this old function as a wrapper around the new one.</li>
<li>Deprecating this function.</li>
</ol>
<hr>
<p>Note that the <code>query</code> in your function is not the same as the <code>query</code> declared outside the function.</p>
|
Error Handling (Java) <p>Fairly easy question, but I was basically given code to debug and I've fixed all errors but one. When trying to make the program more friendly and include error handling, I found that the error message is thrown even if the condition is satisfied (that is, the number in the array that a user searches for actually exists within the array). Not looking for a direct answer, just a hint. I've tried using combinations of if/else as well as moving around curly braces.</p>
<pre><code> Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find: ");
try {
int number = input.nextInt();
int index = Arrays.binarySearch(array, number);
for (int i = 0; i < array.length; i++) {
if ( array[i] == number )
System.out.println("Found " + number + " at index " + index++);
}
System.out.printf("Your number was not found within the array.");
}
catch (InputMismatchException e){
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}
}
</code></pre>
<p>Console output example:</p>
<pre><code>Enter an integer to find: -9
</code></pre>
<blockquote>
<p>Found -9 at index 0
<br> Your number was not found within the array.</p>
</blockquote>
| <p><a href="https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(int[],%20int)" rel="nofollow"><code>Array.binarySearch</code></a> will return the index if it finds the value, otherwise it will return -1. </p>
<p>If <code>index == -1</code>, you can print the "not found message" without entering the loop at all.</p>
<p>Otherwise, if <code>index > 0</code>, then you can enter the loop and iterate over the array to find each index where the value is a match.</p>
<p>This is required if you want a message for multiple matches as binarySearch will just return the the first index the value was found at. </p>
<p>As an aside, binarySearch requires the array to be sorted first, otherwise the results will be undefined. I don't know if this is a problem as array is declared outside of the example.</p>
<pre><code>Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find: ");
try {
int number = input.nextInt();
int index = Arrays.binarySearch(array, number);
if (index > 0) {
for (int i = 0; i < array.length; i++) {
if ( array[i] == number ) {
System.out.println("Found " + number + " at index " + i);
}
}
} else {
System.out.printf("Sorry, your number wasn't found.");
}
}
catch (InputMismatchException e) {
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}
</code></pre>
|
What is clazz used for in "private static Class clazz = SnappyDecompressor.class" source file? <p>I am studying the compressor implementation (in Java) for Snappy, Zlib and others. Near the top of the source file is this line below. Can anyone explain to me what it means?</p>
<pre><code>HACK - Use this as a global lock in the JNI layer
@SuppressWarnings({"unchecked", "unused"})
private static Class clazz = SnappyDecompressor.class;
</code></pre>
<p>I understand, for example, in Snappy, SnappyDecompressor.java is essentially a wrapper for snappy C / native implementation, and to make calls to that C implementation, the Java layer makes calls through JNI interface. </p>
<p>The top part of the source for snappy (Java wrapper), SnappyDecompressor.java is here:</p>
<pre><code>package org.apache.hadoop.io.compress.snappy;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.compress.Decompressor;
/**
* A {@link Decompressor} based on the snappy compression algorithm.
* http://code.google.com/p/snappy/
*/
public class SnappyDecompressor implements Decompressor {
private static final Log LOG =
LogFactory.getLog(SnappyCompressor.class.getName());
private static final int DEFAULT_DIRECT_BUFFER_SIZE = 64 * 1024;
// HACK - Use this as a global lock in the JNI layer
@SuppressWarnings({"unchecked", "unused"})
private static Class clazz = SnappyDecompressor.class;
</code></pre>
<p><a href="https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/io/compress/snappy/SnappyDecompressor.java" rel="nofollow">Full source</a></p>
| <p>As indicated in the comment: it is used from the JNI layer, seemingly for some locking from the JNI layer. (<a href="https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/native/src/org/apache/hadoop/io/compress/snappy/SnappyDecompressor.c" rel="nofollow">see the full Decompressor source</a>)</p>
<p>Lines 76, 77:</p>
<pre><code>SnappyDecompressor_clazz = (*env)->GetStaticFieldID(env, clazz, "clazz",
"Ljava/lang/Class;");
</code></pre>
<p>Line 83:</p>
<pre><code>jobject clazz = (*env)->GetStaticObjectField(env,thisj, SnappyDecompressor_clazz);
</code></pre>
<p>Lines 100 to 102:</p>
<pre><code>LOCK_CLASS(env, clazz, "SnappyDecompressor");
const char* compressed_bytes = (const char*)(*env)->GetDirectBufferAddress(env, compressed_direct_buf);
UNLOCK_CLASS(env, clazz, "SnappyDecompressor");
</code></pre>
|
How do BluRay players or washing machine run Java programs? <p>What OS do they use for example and how to they boot up so quickly (compared to a raspberry pi)?</p>
| <p>Currently, they are two option exiting: </p>
<ul>
<li>they are running a custom piece of software that support a jvm</li>
<li>they are running a minimum version of a linux , just what's enough to run the jvm, everything else is disabled / removed.</li>
</ul>
<p>It's booting that fast because it has only the piece of code needed to run a minimal jvm, and everything else is disabled in opposition of the raspberry pi who has a complete kernel, with a lot of modules, a desktop environment, etc, ... to load.</p>
|
Find the patient who were attended by the highest number of doctors? <p>I'm working with these tables:</p>
<p><strong>TABLE Adm_Med:</strong></p>
<blockquote>
<p>Adm_ID /*ID Admission to the Hospital</p>
<p>Med_ID </p>
<p>Doc_ID /*ID Doctor who attended the patient of the corresponding Adm_ID</p>
</blockquote>
<p><strong>TABLE Admission:</strong></p>
<blockquote>
<p>Adm_ID</p>
<p>Pat_ID /*ID Patient</p>
<p>Date_Admission</p>
<p>Date_Discharge</p>
</blockquote>
<p><strong>TABLE Patient:</strong></p>
<blockquote>
<p>Pat_ID</p>
<p>Pat_Lastname</p>
<p>Pat_Firstname</p>
<p>Birthdate</p>
</blockquote>
<p>I would like the query to return something like:</p>
<blockquote>
<p>Adm_ID | Pat_Lastname | Pat_Firstname | Numberattentions</p>
</blockquote>
<p><strong>But I have two doubts:</strong></p>
<blockquote>
<p>1) In comparison with the script I wrote (see below), is there a
more efficient one that gives the result above? I feel I wrote a lot.</p>
<p>2) Up to now I've just been able to get the first 3 columns. I have no
idea how to put <code>Numberattentions</code> column. I've been trying to do it, but I get an error every time.</p>
</blockquote>
<p>My attempt (here I explain step by step what I've done, but at the end is the complete query. If you don't want to read the all thing):</p>
<p>I counted the number of doctors who attended a patient in a given <code>Adm_ID</code></p>
<pre><code>SELECT Adm_ID, COUNT(doc_id) as numdoc
FROM Adm_Med
GROUP BY Adm_ID
</code></pre>
<p>Then took the max. of those attentions</p>
<pre><code>SELECT MAX(numdoc)
FROM (SELECT Adm_ID, COUNT(doc_id) as numdoc
FROM Adm_Med
GROUP BY Adm_ID) temp
</code></pre>
<p>Matched it with the corresponding <code>Adm_ID</code></p>
<pre><code>SELECT Adm_ID
FROM Adm_Med
GROUP BY Adm_ID
HAVING COUNT(doc_id) IN (SELECT MAX(numdoc)
FROM (SELECT Adm_ID, COUNT(doc_id) as numdoc
FROM Adm_Med
GROUP BY Adm_ID) temp)
</code></pre>
<p>Formed an Inner Join between the tables <code>Admission</code> and <code>Patient</code>, matching, through a <code>WHERE ... IN</code> clause, the <code>Admission.Adm_ID</code> with the <code>Adm_ID</code> for the Attention with the highest numbers of doctors (this is final script I got):</p>
<pre><code>SELECT Adm_ID, Pat_Lastname, Pat_Firstname
FROM Admission a
INNER JOIN Patient p
ON a.Pat_ID=p.Pat_ID
WHERE Adm_ID IN (SELECT Adm_ID
FROM Adm_Med
GROUP BY Adm_ID
HAVING COUNT(doc_id) IN
(SELECT MAX(numdoc)
FROM (SELECT Adm_ID, COUNT(doc_id) as numdoc
FROM Adm_Med
GROUP BY Adm_ID) temp))
</code></pre>
| <p>Since your previous question was related to MySQL I'm guessing that also this one uses MySQL.</p>
<p>And as such, MySQL sadly doesn't support Common Table Expressions (the WITH clause). Which would have allowed the re-use of a query to calculate the max.</p>
<p>So the sql below should return what I think you're looking for. </p>
<p>But i.m.h.o., it's too wordy.
The golfcoder in me is weeping over it. So I'm curious to see if someone can find a more concise way of doing it.</p>
<pre class="lang-sql prettyprint-override"><code>select q1.Adm_ID, p.Pat_Firstname, p.Pat_Lastname, q1.TotalDoctors as Numberattentions
from (
select m.Adm_ID, a.Pat_ID, count(m.Doc_ID) as TotalDoctors
from Admission a
join Adm_Med m on (a.Adm_ID = m.Adm_ID)
group by m.Adm_ID, a.Pat_ID
) q1
join (
select Pat_ID, max(TotalDoctors) as MaxTotalDoctors
from (
select a.Pat_ID, count(m.Doc_ID) as TotalDoctors
from Admission a
join Adm_Med m on (a.Adm_ID = m.Adm_ID)
group by m.Adm_ID, a.Pat_ID
) q0
group by Pat_ID
) q2
on (q1.Pat_ID = q2.Pat_ID and q1.TotalDoctors = q2.MaxTotalDoctors)
left join Patient p on (q1.Pat_ID = p.Pat_ID);
</code></pre>
<p>Some test data :</p>
<pre><code>create table Adm_Med (Adm_ID int, Med_ID int, Doc_ID int);
insert into Adm_Med (Adm_ID, Med_ID, Doc_ID) values
(101,201,301),(101,202,302),(102,203,301),(102,204,302),(102,205,303),
(103,201,301),(103,202,302),(104,203,301),(104,204,302),(104,205,303);
create table Admission (Adm_ID int, Pat_ID int, Date_Admission date, Date_Discharge date);
insert into Admission (Adm_ID, Pat_ID, Date_Admission, Date_Discharge) values
(101,401,'2016-01-01','2016-02-01'),(102,401,'2016-03-01','2016-04-01'),
(103,402,'2016-01-01','2016-02-01'),(104,402,'2016-03-01','2016-04-01');
create table Patient (Pat_ID int, Pat_Firstname varchar(30), Pat_Lastname varchar(30), Birthdate date);
insert into Patient (Pat_ID, Pat_Firstname, Pat_Lastname, Birthdate) values
(401,'John','Doe','1941-05-03'),(402,'Jane','Doe','1942-06-04');
</code></pre>
<p>For only 1 patient, a shorter SQL can be used:</p>
<pre><code>select m.Adm_ID, p.Pat_Firstname, p.Pat_Lastname, count(m.Doc_ID) as Numberattentions
from Admission a
join Adm_Med m on (a.Adm_ID = m.Adm_ID)
join Patient p on (a.Pat_ID = p.Pat_ID)
where p.Pat_ID = 402
group by m.Adm_ID, a.Pat_ID
order by Numberattentions desc
limit 1;
</code></pre>
|
Gesture recognizer on a circular view <p>In each cell of my collection view is a circular UIView. This has been achieved by creating a custom subclass of <code>UIView</code>, which I have called <code>CircleView</code>, and setting <code>layer.cornerRadius = self.frame.size.width/2</code> in the subclass' <code>awakeFromNib()</code></p>
<p>I want to add a gesture recognizer to each CircleView. I have done this in the collection view's <code>cellForItemAtIndexPath</code>:</p>
<pre><code>let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
cell.circleView.addGestureRecognizer(gestureRecognizer)
</code></pre>
<p>The problem is that the gesture recognizer is called whenever a tap occurs anywhere within the bounds of the original square UIView. I want to only recognize taps that occur within the circle.</p>
<p>I have tried to solve this issue in the following ways:</p>
<p>In the CircleView's <code>awakeFromNib()</code> I set <code>self.clipsToBounds = true</code> (no effect)</p>
<p>Also in the CircleView's <code>awakeFromNib()</code> I set <code>layer.masksToBounds = true</code> (no effect)</p>
<p>Thank you in advance for your ideas and suggestions.</p>
| <p>You can override this method in CircleView:</p>
<pre><code>override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let center = CGPoint(x: bounds.size.width/2, y: bounds.size.height/2)
return pow(center.x-point.x, 2) + pow(center.y - point.y, 2) <= pow(bounds.size.width/2, 2)
}
</code></pre>
<p><a href="https://i.stack.imgur.com/S45Yd.png" rel="nofollow"><img src="https://i.stack.imgur.com/S45Yd.png" alt="enter image description here"></a></p>
<p>All touches not belonging to the circle will be ignored.</p>
<p><strong>More details:</strong></p>
<p><a href="https://developer.apple.com/reference/uikit/uiview/1622469-hittest" rel="nofollow">https://developer.apple.com/reference/uikit/uiview/1622469-hittest</a>
<a href="https://developer.apple.com/reference/uikit/uiview/1622533-point" rel="nofollow">https://developer.apple.com/reference/uikit/uiview/1622533-point</a></p>
<p>The main point is that you don't need to call neither <code>hitTest</code> nor <code>pointInside</code> methods, you just override them in your custom view and system will call them whenever it needs to know if a touch should be handled by this view.</p>
<p>In your case you've got a <code>UITableViewCell</code> with a <code>CircleView</code> in it, right? You've added a gesture recognizer to <code>CircleView</code> and overriden <code>pointInside</code> method, so a touch will be handled by <code>CircleView</code> itself if a touch point is inside the circle, otherwise event will be passed further, handled by cell and therefore <code>didSelectRowAtIndexPath</code> will be called.</p>
|
Attributed string font formatting changes when dequeuing reusable UITableViewCell <p>I have a <code>UITableView</code> that contains cells where I'm setting an <code>NSAttributedString</code> on a <code>UILabel</code>. The <code>NSAttributedString</code> has sections that are HTML bolded using <code><b>%@</b> by <b>%@</b></code>, and they render correctly on the first pass however when the cell is called again the entire string is in bold, rather than the individual sections.</p>
<p>I prepare the <code>NSAttributedString</code> with this function. </p>
<pre><code>- (NSAttributedString *)attributedStringForString:(NSString *)string forFont:(UIFont *)font {
NSLog(@"Get attributed string");
string = [string stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx; color:#000000;}</style>",
font.fontName,
font.pointSize]];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSAttributedString *labelString = [[NSAttributedString alloc] initWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:nil];
return labelString;
}
</code></pre>
| <p>A couple ways to solve this:</p>
<p>1) </p>
<p>In your custom UITableViewCell, you should implement <code>prepareForReuse</code>:</p>
<pre><code>-(void)prepareForReuse{
[super prepareForReuse];
// Then Reset here back to default values that you want.
self.label.font = [UIFont systemFontOfSize: 12.0f];
}
</code></pre>
<p>2)</p>
<p>After you dequeue your table view cell in your <code>cellForRowAtIndexPath</code> method, you can do something like:</p>
<pre><code>UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if(cell)
{
cell.textLabel.font = [UIFont systemFontOfSize: 12.0f];
}
</code></pre>
|
Pandas flatten hierarchical index on non overlapping columns <p>I have a dataframe, and I set the index to a column of the dataframe. This creates a hierarchical column index. I want to flatten the columns to a single level. Similar to this question - <a href="http://stackoverflow.com/questions/14507794/python-pandas-how-to-flatten-a-hierarchical-index-in-columns">Python Pandas - How to flatten a hierarchical index in columns</a>, however, the columns do not overlap (i.e. 'id' is not at level 0 of the hierarchical index, and other columns are at level 1 of the index).</p>
<pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])
df.set_index('id', inplace=True)
A B
id
101 3 x
102 5 y
</code></pre>
<p>Desired output is flattened columns, like this:</p>
<pre><code>id A B
101 3 x
102 5 y
</code></pre>
| <p>You are misinterpreting what you are seeing.</p>
<pre><code> A B
id
101 3 x
102 5 y
</code></pre>
<p>Is not showing you a hierarchical column index. <code>id</code> is the name of the row index. In order to show you the name of the index, pandas is putting that space there for you.</p>
<p>The answer to your question depends on what you really want or need.</p>
<p>As the <code>df</code> is, you can dump it to a <code>csv</code> just the way you want:</p>
<pre><code>print(df.to_csv(sep='\t'))
id A B
101 3 x
102 5 y
</code></pre>
<hr>
<pre><code>print(df.to_csv())
id,A,B
101,3,x
102,5,y
</code></pre>
<hr>
<p>Or you can alter the <code>df</code> so that it displays the way you'd like</p>
<pre><code>print(df.rename_axis(None))
A B
101 3 x
102 5 y
</code></pre>
<hr>
<p><strong><em>please do not do this!!!!</em></strong><br>
I'm putting it to demonstrate how to manipulate</p>
<p>I could also keep the index as it is but manipulate both column and row index names to print how you would like.</p>
<pre><code>print(df.rename_axis(None).rename_axis('id', 1))
id A B
101 3 x
102 5 y
</code></pre>
<p>But this has named the columns' index <code>id</code> which makes no sense.</p>
|
Get a Notification in Android when a Firebase child has been added <p>I am trying to get an android notification when a Fire base Database child has been added to the database using listeners, but unable to get the notification. I have coded this little test app which doesn't show an notification when the app is run, or even on background. Can someone please look into this, and help me out, I am still a beginner, a little help would be wonderful!</p>
<pre><code>package com.fayaz.firebasenotify;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private FirebaseDatabase myFirebaseRef = FirebaseDatabase.getInstance();
private DatabaseReference myRef = myFirebaseRef.getReference();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
public void sendNotification(View view) {
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Firebase Push Notification");
builder.setContentText("Hello this is a test Firebase notification, a new database child has been added");
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.i("FirebaseError", databaseError.getMessage());
}
};
myRef.addValueEventListener(valueEventListener);
}
}
</code></pre>
| <p>You should use ChildEventListener,</p>
<pre><code> super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRootRef = FirebaseDatabase.getInstance().getReference();
builder = new NotificationCompat.Builder(this);
mRootRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Firebase Push Notification");
builder.setContentText("Hello this is a test Firebase notification, a new database child has been added");
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
</code></pre>
<p>Make sure you can read the data from the database (check security rules).</p>
|
Add Parse server to an already existing project <p>I have a project and I want to add Parse to it. I installed the Parse server in my PC, downloaded the SDK from their website and it worked perfectly fine.<br>
However, I don't want to use the SDK from their website, I just want to add the libraries to my project.</p>
<p>Here is what I did: I copied these libraries files into my project libs folder</p>
<pre><code>'libs/parse-android-1.13.1.jar'
'libs/bolts-android-1.2.0.jar'
</code></pre>
<p>and here is my code : </p>
<p>in the build.gradle file :</p>
<pre><code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
compile files('libs/parse-android-1.13.1.jar')
compile files('libs/bolts-android-1.2.0.jar')
}
</code></pre>
<p>I added the dependencies as above.</p>
<p>for the main Activity:</p>
<pre><code>public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("kooora.com100plus")
.clientKey("kooora.com100plusMasterKey")
.server("http://10.0.2.2:1337/parse/")
.build()
);
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Log.i("Parse", "Save Succeeded");
} else {
Log.i("Parse", e.getMessage());
}
}
});
}
}
</code></pre>
<p>Here is the log for the error I get :</p>
<pre><code>10-16 06:34:42.539 25428-25428/? I/art: Not late-enabling -Xcheck:jni (already on)
10-16 06:34:42.563 25428-25436/? E/art: Failed writing handshake bytes (-1 of 14): Broken pipe
10-16 06:34:42.563 25428-25436/? I/art: Debugger is no longer active
10-16 06:34:42.696 25428-25428/? D/AndroidRuntime: Shutting down VM
10-16 06:34:42.696 25428-25428/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sabirmoglad.big_boss, PID: 25428
java.lang.NoClassDefFoundError: Failed resolution of: Lbolts/TaskCompletionSource;
at com.parse.ParseTaskUtils.callbackOnMainThreadAsync(ParseTaskUtils.java:100)
at com.parse.ParseTaskUtils.callbackOnMainThreadAsync(ParseTaskUtils.java:72)
at com.parse.ParseTaskUtils.callbackOnMainThreadAsync(ParseTaskUtils.java:59)
at com.parse.ParseObject.saveInBackground(ParseObject.java:1529)
at com.example.sabirmoglad.big_boss.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassNotFoundException: Didn't find class "bolts.TaskCompletionSource" on path: DexPathList[[zip file "/data/app/com.example.sabirmoglad.big_boss-2/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at com.parse.ParseTaskUtils.callbackOnMainThreadAsync(ParseTaskUtils.java:100)Â
at com.parse.ParseTaskUtils.callbackOnMainThreadAsync(ParseTaskUtils.java:72)Â
at com.parse.ParseTaskUtils.callbackOnMainThreadAsync(ParseTaskUtils.java:59)Â
at com.parse.ParseObject.saveInBackground(ParseObject.java:1529)Â
at com.example.sabirmoglad.big_boss.MainActivity.onCreate(MainActivity.java:31)Â
at android.app.Activity.performCreate(Activity.java:5937)Â
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)Â
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)Â
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)Â
at android.app.ActivityThread.access$800(ActivityThread.java:144)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:135)Â
at android.app.ActivityThread.main(ActivityThread.java:5221)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at java.lang.reflect.Method.invoke(Method.java:372)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)Â
Suppressed: java.lang.ClassNotFoundException: bolts.TaskCompletionSource
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 19 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code></pre>
<p>I don't know what went wrong! I just get a runtime error and it stops working</p>
<hr>
<p>UPDATE:</p>
<p>As suggested in the comments, I put the initialization in my Application class,<br>
in fact I copied the class from the original SDK but it seems like this initialization doesn't execute,</p>
<p>here is the class I added from the original SDK:</p>
<pre><code>public class StarterApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("kooora.com100plus")
.clientKey("kooora.com100plusMasterKey")
.server("http://10.0.2.2:1337/parse/")
.build()
);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
// defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
}
</code></pre>
| <p>Firstly, adding those two libs lines to the Gradle file was not necessary. This one line includes all JAR files on its own. </p>
<pre><code>compile fileTree(dir: 'libs', include: ['*.jar'])
</code></pre>
<p>Now, I generally recommend that you try your best to avoid JAR libraries when you can find the dependencies in JCenter or Maven Central (look those up, if you are unsure). Reason being - transitive dependencies get included for you, version management requires some number changes, not overwriting a file, etc. </p>
<p>Then, the Class not found error could originate from using an outdated version of the libraries. </p>
<p>All in all, remove the JAR files, compile the libraries with these dependencies. (latest versions in comments above) </p>
<pre><code>dependencies {
// other stuff
compile 'com.parse:parse-android:1.13.1'
compile 'com.parse.bolts:bolts-tasks:1.4.0'
compile 'com.parse.bolts:bolts-applinks:1.4.0'
}
</code></pre>
|
Jersey multipart getFileName() has concatenated path <p>I am trying to get a file upload working with Java + Jersey + multipart + Tomcat + HTML/CSS/JS.</p>
<p>For testing purposes I'm just trying to upload some arbitrary file from my Downloads folder and have it written to my desktop.</p>
<p>My only problem seems to be that when I try to get the filename of the uploaded file via <code>fileDetail.getFileName();</code> somehow I'm getting a concatenated path in with the filename ("C:UsersHackRDownloadsstackexample.csv").</p>
<p>My plan (following a tutorial) was to then prepend the destination directory to the filename:</p>
<pre><code> String uploadedFileLocation = "C:/Users/HackR/Desktop/"
+ fileDetail.getFileName();
</code></pre>
<p>and write it out. However it ends up trying to write it to somethings like this:</p>
<pre><code>C:/Users/HackR/Desktop/C:UsersHackRDownloadsstackexample.csv
</code></pre>
<p>which actually just creates a 0kb file named <code>C</code> on my desktop.</p>
<p>How can I get the actual filename the way I need it for this example (i.e. no path)?</p>
<p>This is my entire file upload service:</p>
<pre><code>package com.mkyong.rest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
@Path("/file")
public class UploadFileService {
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "C:/Users/HackR/Desktop/"
+ fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
| <p>The concatenated file name is a result of using the browser internal to Eclipse, which may not properly support your HTML, CSS, JS, etc, especially if you're using Angular JS or any webkit technologies, even indirectly.</p>
<p>The eclipse internal browser is really just a native browser control :) On a Mac, that makes it use Safari, the engine of which is webkit.</p>
<p>Make your work with Safari, or maybe with Chrome, which is still very similar because it's based on a relatively recent fork of webkit, then it should work in the eclipse internal browser on a Mac, too :)</p>
<p>As your post suggests that you're on a Windows machine, you need to instead make your code work with your installed Internet Explorer, because that's what eclipse uses on Windows.</p>
<p>Good luck in any case!</p>
|
What would be the best compound index for this MySQL query? <p>What would be the best compound index for this MySQL query?</p>
<pre><code>SELECT
c.id, c.customer_id, c.service_id, c.origin_id, c.title, c.state, c.start_date_time
FROM
calendar_events c
WHERE
c.customer_id = 1234
AND c.state IN ('unconfirmed', 'confirmed')
AND c.start_datetime BETWEEN '2016-10-15 00:00:00' AND '2016-10-15 23:59:59';
</code></pre>
| <p>Probably this:</p>
<pre><code>INDEX(customer_id, -- '=' comes first
state, -- 'IN' sometimes works ok in the middle
start_datetime) -- nothing after a 'range' will be used
</code></pre>
<p>Run <code>EXPLAIN SELECT ...</code> It will probably say "MRR" in the <code>Other</code> column. I call this the 'leapfrog' optimization. In your case it will easily reach into the start of index rows with 1234 & 'unconfirmed' & 00:00. Then it will range scan consecutive entries for that day.</p>
<p>Then it will leap over to 1234 & 'confirmed' & 00:00 for another scan.</p>
<p>That adds to two BTree probes into the index, plus two index scans. The is very efficient.</p>
<p>Then, for each row in the index, it will reach over (using the <code>PRIMARY KEY</code>) to get the other columns needed.</p>
<p>Recommended pattern for date&time range:</p>
<pre><code>AND c.start_datetime >= '2016-10-15'
AND c.start_datetime < '2016-10-15' + INTERVAL 1 DAY
</code></pre>
|
IOS Swift ongoing notifications <p>I wanted to know if it is possible to create ongoing notifications in IOS similar to the ones in Android. I have seen e.g. with Voice Recording applications, that after pressing record, the user can click the home button and red bar covers the top bar (same thing if the user is on a call). </p>
<p>I want to create a stop-watch with the additional functionality of the top bar ongoing notification so that the user knows that the stopwatch is running. </p>
<p>Thanks</p>
| <p>Modifying the status bar is not possible.</p>
<p>The best you can achieve is with a widget, where you can start/stop your stopwatch, etc. Starting with iOS 10, you can have rich notifications as well, but they still have to be triggered by the user, and I don't think that fits what you need.</p>
|
getId from selected EditText android <p>this is my first question, I've made a code to add views from a SQLite database and I'd like to select an EditText I've added and when I change this value do an action. I don't know the Id of this EditText so I can't use findByValue on this case. How can I get this? Here is my code:</p>
<pre><code>LinearLayout pantalla;
int[] edits;
int adicionales = 0;
int IdSelected; //I want to put the Id here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_platos);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
edits = getResources().getIntArray(R.array.editTexts); //these are the Id values that I've created on String file
pantalla = (LinearLayout) findViewById(R.id.pantallaPlatos);
CargarPlatos(); //this calls to create all the EditTexts
}
public void CargarPlatos() {
pantalla.removeAllViews();
List<tablaPlatos> Platos = Consumo.db.getAllPlatos();
int i = 0;
for (tablaPlatos platos : Platos) {
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
pantalla.addView(linearLayout);
EditText item = new EditText(this);
String log = platos.getName();
item.setText(log);
item.setId(edits[i]);
;
i++;
linearLayout.addView(item);
EditText item2 = new EditText(this);
String log2 = platos.getValue();
item2.setText(log2);
item2.setId(edits[i]);
item2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
i++;
linearLayout.addView(item2);
}
}
// When I click on an EditText I want to know his Id
@Override
public void onClick(View v) {
IdSelected=v.getId();
//And then do something
}
</code></pre>
<p><a href="https://i.stack.imgur.com/biMHZ.jpg" rel="nofollow">ScreenCapture of this code</a></p>
<p>Really hope you can help me with this. Thank you.</p>
| <p>Ok guys, thanks for trying to help me, I found my solution with OnGlobalFocusChangeListener</p>
<p>I added this code on the OnCreate:</p>
<pre><code> pantalla.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
@Override
public void onGlobalFocusChanged(View oldFocus, View newFocus) {
if (oldFocus!=null){
Toast.makeText(Platos.this, "Id: " + String.valueOf(oldFocus.getId()), Toast.LENGTH_SHORT).show();
}
if (newFocus!=null){
Toast.makeText(Platos.this, "Id: " + String.valueOf(newFocus.getId()), Toast.LENGTH_SHORT).show();
}
}
});
</code></pre>
<p>with this I can see the Id of the focused EditText</p>
|
Make python read 12 from file as 12 not 1 and 2 <p>Trying to make a program that provides the price to different numbers of stages. In "tripss.txt",third line is the number 12, python interprets it as 1 and 2 instead and gives the price for each rather than the number as a whole, any way to fix it to that it's read as 12?.</p>
<pre><code>infile = open("tripss.txt","r")
customer_one= infile.readline().strip("\n")
customer_two= infile.readline().strip("\n")
customer_three= infile.readline().strip("\n")
one_to_three_stages="euro 1.55"
four_to_seven_stages="euro 1.85"
seven_to_eleven_stages="euro 2.45"
more_than_eleven_stages="euro 2.85"
cheapest = ["1","2","3"]
cheap = ["4","5","6","7"]
expensive = ["7","8","9","10","11"]
for number in customer_three:
if number in cheapest:
print one_to_three_stages
elif number in cheap:
print four_to_seven_stages
elif number in expensive:
print seven_to_eleven_stages
else:
print more_than_eleven_stages
</code></pre>
| <p>In your code it seems that you want to consider customer_three as a list of strings. However in your code it is a string, not a list of strings, and so the for loop iterates on the characters of the string ("1" and "2").<br>
So I suggest you to replace: </p>
<pre><code>customer_three= infile.readline().strip("\n")
</code></pre>
<p>with: </p>
<pre><code>customer_three= infile.readline().strip("\n").split()
</code></pre>
|
bind entry and button <p>i have a program which start by asking user his code so user will type code in Entry and click button or click enter in keyboard i made two similar function with different inputs to deal with this </p>
<pre><code>b1 = Button(root,text='login',command = Login_click)
b1.pack()
b1.bind('<Return>',Login_bind)
def Login_click(self):
do some thing
def Login_bind(self,event):
do something
</code></pre>
<p>and it works very fine but is there any way to make only one function deal with clicked and enter key</p>
| <p>You can simply define a function with <code>event=None</code> as a default value so that it is optional and then use the same function for both.</p>
<pre><code>b1 = Button(root,text='login',command = Login_click_and_bind)
b1.pack()
b1.bind('<Return>',Login_click_and_bind)
def Login_click_and_bind(self,event=None):
do something
</code></pre>
|
Replace [X] with [Y] in texarea on submit <p>I have a form, where users are to insert musical chords as [Am], [D], etc inside a textarea. A chord letter enclosed by brackets.</p>
<p>I want to prevent users from entering northern europian variations of [H], and have them replaced by english [B] on form submit.</p>
<p>How can I set up a replace function that does something like this:</p>
<pre><code>[H] -> [B]
[Hm] -> [Bm]
[Hm7] -> [Bm7]
[h] -> [H]
[h7] -> [H7]
</code></pre>
<p>I should be enough to globally replace H/h inside a bracket with a capital B inside the same bracket.</p>
<p>Is there a smart replace function you would recommend?</p>
| <p>You could use this <code>replace()</code> call:</p>
<pre><code>.replace(/\[H(.*?)\]/gi, '[B$1]')
</code></pre>
<p>Snippet:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.forms[0].onsubmit = function() {
var txt = document.querySelector('textarea');
txt.textContent = txt.textContent.replace(/\[H(.*?)\]/gi, '[B$1]');
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#">
<textarea>test [H] and [H7m], but also [h] and [h7].</textarea>
<input type="submit" value="Submit">
</form></code></pre>
</div>
</div>
</p>
|
Java unchecked method invocation with ArrayList <p>When I run my code I get this warning: </p>
<pre><code>warning: [unchecked] unchecked method invocation: method addAll in interface List is applied to given types
snakeDotlist.addAll(genFirstDots());
required: Collection<? extends E>
found: List
where E is a type-variable:
E extends Object declared in interface List
</code></pre>
<p>code:</p>
<pre><code>initDisplay();
List<Sprite> snakeDotlist = new ArrayList<>();
snakeDotlist.addAll(genFirstDots());
Sprite tokenSprite = new Sprite((genRandomNumber(0, 64)), (genRandomNumber(0, 48)), 16, 16, "res/snakedot.png");
while(!Display.isCloseRequested())
{
if (hasCollided(tokenSprite, snakeDotlist.get(0)))
{
tokenSprite.updateToken(true);
snakeDotlist.get(0).score += 1;
snakeDotlist.addAll(genNewDots((int)snakeDotlist.get(0).prev1x, (int)snakeDotlist.get(0).prev1y, (int)snakeDotlist.get(0).prev2x, (int)snakeDotlist.get(0).prev1y));
}
</code></pre>
<p>.</p>
<pre><code> public static List genFirstDots()
{
List<Sprite> list = new ArrayList<>();
list.add(new Sprite(3, 0, 16, 16, "res/snakedot.png"));
list.add(new Sprite(2, 0, 16, 16, "res/snakedot.png"));
list.add(new Sprite(1, 0, 16, 16, "res/snakedot.png"));
list.add(new Sprite(0, 0, 16, 16, "res/snakedot.png"));
return list;
}
</code></pre>
<p>I looked at a few other posts that said to change the declaration of snakeDotList from </p>
<pre><code>List<Sprite> snakeDotlist = new ArrayList<Sprite>();
</code></pre>
<p>to</p>
<pre><code>List<Sprite> snakeDotlist = new ArrayList<>();
</code></pre>
<p>but I still get the warning messages and I don't know how to solve it, any help?</p>
| <p>You should change this:</p>
<pre><code>public static List genFirstDots()
</code></pre>
<p>to this:</p>
<pre><code>public static List<Sprite> genFirstDots()
</code></pre>
<p>The reason why the warning appears is because you are returning a <code>List</code> in <code>genFirstDots()</code> but you're adding the returned value to a <code>List<Sprite></code>.</p>
<p>When no generic type arguments are given, generic types implicitly has an <code>Object</code> type argument, so <code>List</code> is actually <code>List<Object></code>. When you try to append a list of objects to a list of sprites, the objects that the object list stores might not be compatible with <code>Sprite</code> and can't be added to the sprite list. Hence the warning.</p>
|
Convert QueryDict into list of arguments <p>I'm receiving via POST request the next payload through the view below:</p>
<pre><code>class CustomView(APIView):
"""
POST data
"""
def post(self, request):
extr= externalAPI()
return Response(extr.addData(request.data))
</code></pre>
<p>And in the <code>externalAPI</code> class I have the <code>addData()</code> function where I want to convert <em>QueryDict</em> to a simple list of arguments:</p>
<pre><code>def addData(self, params):
return self.addToOtherPlace(**params)
</code></pre>
<p>In other words, what I get in params is somethin like:</p>
<pre><code><QueryDict: {u'data': [u'{"object":"a","reg":"1"}'], u'record': [u'DAFASDH']}>
</code></pre>
<p>And I need to pass it to the addToOtherPlace() function like:</p>
<pre><code>addToOtherPlace(data={'object':'a', 'reg': 1}, record='DAFASDH')
</code></pre>
<p>I have tried with different approaches but I have to say I'm not very familiar with dictionaries in python.</p>
<p>Any help would be really appreciated.</p>
<p>Thanks!</p>
| <p>You can write a helper function that walks through the <em>QueryDict</em> object and converts valid <em>JSON</em> objects to Python objects, string objects that are digits to integers and returns the first item of lists from lists:</p>
<pre><code>import json
def restruct(d):
for k in d:
# convert value if it's valid json
if isinstance(d[k], list):
v = d[k]
try:
d[k] = json.loads(v[0])
except ValueError:
d[k] = v[0]
# step into dictionary objects to convert string digits to integer
if isinstance(d[k], dict):
restruct(d[k])
elif d[k].isdigit():
d[k] = int(d[k])
params = {u'data': [u'{"object":"a","reg":"1"}'], u'record': [u'DAFASDH']}
restruct(params)
print(params)
# {'record': 'DAFASDH', 'data': {'object': 'a', 'reg': 1}}
</code></pre>
<p>Note that this approach modifies the initial object <em>in-place</em>. You can make a <code>deepcopy</code>, and modify the copy instead if you're going to keep the original object intact:</p>
<pre><code>import copy
def addData(self, params):
params_copy = copy.deepcopy(params)
restruct(params_copy)
return self.addToOtherPlace(**params_copy)
</code></pre>
|
Cmake don't find Freetype on Windows 10 <p>I'm trying to use Cmake <a href="https://cmake.org/download/" rel="nofollow">https://cmake.org/download/</a> to convert the source code of EmulationStation (<a href="https://github.com/Herdinger/EmulationStation" rel="nofollow">https://github.com/Herdinger/EmulationStation</a>) to VS, so I can make a translation, and later recompile it.</p>
<p>But Cmake (3.7.0) keeps showing me errors:</p>
<blockquote>
<p>CMAKE_CONFIGURATION_TYPES: Debug;Release;MinSizeRel;RelWithDebInfo
CMAKE_INSTALL_PREFIX: C:/Program Files (x86)/emulationstation
FREETYPE_INCLUDE_DIR_freetype2:
FREETYPE_INCLUDE_DIR_freetype2-NOTFOUND FREETYPE_INCLUDE_DIR_ft2build:
FREETYPE_INCLUDE_DIR_ft2build-NOTFOUND GLSystem: OpenGL ES</p>
</blockquote>
<p>Any ideas (or even a tutorial about it) are very welcome, thank you.</p>
| <p>Sorry if someone thinks the question is "low quality". Anyway, more people can be facing the same issue, so I'll elaborate my own answer and show what I did to solve it (partially).</p>
<p>As explained on EmulationStation page, download all dependencies: SDL2, Boost, FreeImage, FreeType, Eigen3, and cURL. You have to compile Boost, FreeType, and cURL. A branch of ES, from Herdinger, says you have to compile FreeImage, too. The others, you can use precompiled libraries.</p>
<p>Organize your files anyway you need. I've put all of them inside a folder "dependencies" on the root folder of my project.</p>
<p>Open CMake, click "Browse Source..." and browse to the project folder (the ES folder, where the file CmakeLists.txt is). Click "Browse Build..." and find the output folder (create one).</p>
<p>Click "Configure" and select the compiler (I'm using VS2013). Cmake will show some errors, and here you start to point the proper files and folders.</p>
<p><a href="https://i.stack.imgur.com/OdXJs.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/OdXJs.jpg" alt="enter image description here"></a></p>
<p>Sadly, files and folders necessary for ES are a mess, too little information, so I still with errors (now related to Boost). But it's enough to answer this question, I guess. Feel free to correct me in anything if needed.</p>
|
Random Generator max/min values? <p>I have written a method variation:</p>
<pre><code>private int variation() {
int randomNumber = randomGenerator.nextInt(90);
return (randomNumber + handicap)/18 - 2;
}
</code></pre>
<p>Assuming that the handicap is = 18, what are the minimum and maximum values that this method can return?</p>
| <pre><code>Maximum=3;
Minimum=-1.
</code></pre>
<p>From the <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Random.html" rel="nofollow">docs</a> for random </p>
<blockquote>
<p>Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive)</p>
</blockquote>
<p>Therefore, the maximum returnable value of nextInt(90) is 89 and the minimum is 0.</p>
<p>Plugging into your function:
(89 + 18)/18 - 2 = (Technically 3.94444444444 which is rounded down to 3)
(0+18)/18-1=-1</p>
|
Is there a programmatic way in C to determine the number of processes ever used in a group of processes under Linux? <p>I know of the <code>sysinfo()</code> function that returns a <code>procs</code> parameter representing the total number of processes currently running on your Linux system.</p>
<p>However, there is the <code>RLIMIT_NPROC</code> parameter to the <code>setrlimit()</code> and <code>getrlimit()</code> function that limit the number of child processes a process can have.</p>
<p>In order for the system to enforce that number, I would imagine it knows the current number of processes in that <em>group</em>. Is that number readily accessible?</p>
| <p>To enforce the <code>RLIMIT_NPROC</code> limit, linux kernel reads <code>&p->real_cred->user->processes</code> field in <code>copy_process</code> function (on <code>fork()</code> for example)
<a href="http://lxr.free-electrons.com/source/kernel/fork.c?v=4.8#L1371" rel="nofollow">http://lxr.free-electrons.com/source/kernel/fork.c?v=4.8#L1371</a></p>
<pre><code> 1371 if (atomic_read(&p->real_cred->user->processes) >=
1372 task_rlimit(p, RLIMIT_NPROC)) {
</code></pre>
<p>or in <code>sys_execve</code> (<code>do_execveat_common</code> in fs/exec.c):</p>
<pre><code>1504 if ((current->flags & PF_NPROC_EXCEEDED) &&
1505 atomic_read(&current_user()->processes) > rlimit(RLIMIT_NPROC)) {
1506 retval = -EAGAIN;
1507 goto out_ret;
</code></pre>
<p>So, if the <code>processes</code> is larger than RLIMIT_NPROC, function will fail. This field is defined as part of <code>struct user_struct</code> (accessed with <a href="http://lxr.free-electrons.com/source/include/linux/cred.h?v=4.8#L118" rel="nofollow"><code>struct cred</code> <em>real_cred</em></a> in <a href="http://code.metager.de/source/xref/linux/stable/include/linux/sched.h#816" rel="nofollow">sched.h</a> as</p>
<pre><code> atomic_t processes; /* How many processes does this user have? */
</code></pre>
<p>So the process count accounting is per-user.</p>
<p>There is decrement of the field in copy_process in case of fail:</p>
<pre><code>1655 bad_fork_cleanup_count:
1656 atomic_dec(&p->cred->user->processes);
</code></pre>
<p>And increment of the field is in <code>copy_cred</code>: <a href="http://code.metager.de/source/xref/linux/stable/kernel/cred.c#313" rel="nofollow">http://code.metager.de/source/xref/linux/stable/kernel/cred.c#313</a></p>
<pre><code>313 /*
314 * Copy credentials for the new process created by fork()
315 *
316 * We share if we can, but under some circumstances we have to generate a new
317 * set.
318 *
319 * The new process gets the current process's subjective credentials as its
320 * objective and subjective credentials
321 */
322 int copy_creds(struct task_struct *p, unsigned long clone_flags)
339 atomic_inc(&p->cred->user->processes);
372 atomic_inc(&new->user->processes);
</code></pre>
<p>man page says that it is per-user limit: <a href="http://man7.org/linux/man-pages/man2/setrlimit.2.html" rel="nofollow">http://man7.org/linux/man-pages/man2/setrlimit.2.html</a></p>
<blockquote>
<pre><code> RLIMIT_NPROC
The maximum number of processes (or, more precisely on Linux,
threads) that can be created for the real user ID of the
calling process. Upon encountering this limit, fork(2) fails
with the error EAGAIN.
</code></pre>
</blockquote>
|
Buttons Dont Work While On Iphone 6 plus and Iphone 7 plus <p>Inside a XIB file I have several buttons. Each button moves to a different point inside the ScrollView. The buttons only work on iPhone 6 Plus and 7 Plus. There is a button in each phrase below:</p>
<p><a href="https://i.stack.imgur.com/JTrjK.png" rel="nofollow"><img src="https://i.stack.imgur.com/JTrjK.png" alt="enter image description here"></a></p>
| <p>Add this code to the view that all the buttons are contained in.</p>
<pre><code>view.layer.borderWidth = 1
</code></pre>
<p>The above will allow you to see where the view is located. My guess is that you will find that the buttons that can't be tapped on are not inside the rectangle defined by their parent view. Therefore, they can't receive taps.</p>
<p>To fix, make sure that the view is large enough to contain all of its child views.</p>
|
How to Edit This <p>I'm trying to mod SKyrim and have to edit my batch file. I need to change each line to look like:</p>
<pre><code>Player.GetInFaction "<Faction ID>" ;;; <Description>
</code></pre>
<p>E.g. :</p>
<pre><code>FACT: (00000013) 'Creature Faction'
</code></pre>
<p>would be:</p>
<pre><code>Player.GetInFaction "00000013" ;;; Creature Faction
</code></pre>
<p>The lines look like this(there are hundreds): </p>
<pre><code>FACT: (00000013) 'Creature Faction'
FACT: (000135A0) 'Thalmor Splinter Faction'
FACT: (00016C2F) 'Black Briar Meadery Faction'
FACT: (00016C30) 'Riften Fishery Faction'
</code></pre>
<p>So how do I quickly edit them? I downloaded Vim but have no idea how to use it.</p>
| <p>Press <code>i</code> to enter edit mode, then <code>esc</code> to exit it. To close vim saving the file just type <code>:wq</code> and press <code>enter</code></p>
|
D3 Brush events - which brush was moved? The left one or the right one? <p>Hopefully the title says it all.</p>
<p>I am handling a D3 brush moved event. And am trying to work out, whether the user moved the left brush or the right brush...?</p>
<p>I really want to avoid storing the mouse position somewhere.</p>
<p>Is there are relatively easy way to work this out..?</p>
| <p>Easiest way I can see:</p>
<pre><code>// bind to at least start and end events
var brush = d3.brushX()
.extent([[0, 0], [width, height]])
.on("start brush end", brushmoved);
// handle it
var bs = "";
function brushmoved() {
var s = d3.event.selection;
if (d3.event.type === "start"){
bs = d3.event.selection;
} else if (d3.event.type === "end"){
if (bs[0] !== s[0] && bs[1] !== s[1]) {
console.log('moved both');
} else if (bs[0] !== s[0]) {
console.log('moved left');
} else {
console.log('moved right');
}
}
</code></pre>
<p>}</p>
<hr>
<p>Full example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<meta charset="utf-8">
<style>
circle {
fill-opacity: 0.2;
transition: fill-opacity 250ms linear;
}
circle.active {
stroke: #f00;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = d3.range(800).map(Math.random);
var svg = d3.select("svg"),
margin = {top: 194, right: 50, bottom: 214, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear().range([0, width]),
y = d3.randomNormal(height / 2, height / 8);
var brush = d3.brushX()
.extent([[0, 0], [width, height]])
.on("start brush end", brushmoved);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
var circle = g.append("g")
.attr("class", "circle")
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("transform", function(d) { return "translate(" + x(d) + "," + y() + ")"; })
.attr("r", 3.5);
var gBrush = g.append("g")
.attr("class", "brush")
.call(brush);
var handle = gBrush.selectAll(".handle--custom")
.data([{type: "w"}, {type: "e"}])
.enter().append("path")
.attr("class", "handle--custom")
.attr("fill", "#666")
.attr("fill-opacity", 0.8)
.attr("stroke", "#000")
.attr("stroke-width", 1.5)
.attr("cursor", "ew-resize")
.attr("d", d3.arc()
.innerRadius(0)
.outerRadius(height / 2)
.startAngle(0)
.endAngle(function(d, i) { return i ? Math.PI : -Math.PI; }));
gBrush.call(brush.move, [0.3, 0.5].map(x));
var bs = "";
function brushmoved() {
var s = d3.event.selection;
if (d3.event.type === "start"){
bs = d3.event.selection;
} else if (d3.event.type === "end"){
if (bs[0] !== s[0] && bs[1] !== s[1]) {
console.log('moved both');
} else if (bs[0] !== s[0]) {
console.log('moved left');
} else {
console.log('moved right');
}
}
if (s == null) {
handle.attr("display", "none");
circle.classed("active", false);
} else {
var sx = s.map(x.invert);
circle.classed("active", function(d) { return sx[0] <= d && d <= sx[1]; });
handle.attr("display", null).attr("transform", function(d, i) { return "translate(" + s[i] + "," + height / 2 + ")"; });
}
}
</script></code></pre>
</div>
</div>
</p>
|
Access page element popup from another window <p>Open a url from base page open.php using </p>
<pre><code>window.location("open1.php");
</code></pre>
<p>in a pop up window</p>
<p>Now I opened another popup on click a button on open1.php using</p>
<pre><code>window.location("open2.php");
</code></pre>
<p>in a now pop up window</p>
<p>Now I want to access the elements of open.php from open2.php using javascript .Something like:</p>
<pre><code>opener.document.getElementById("#any_element_id_on_open.php");
</code></pre>
<p>How can I do So?</p>
| <p>Just use <code>opener.opener</code>.</p>
<p><strong>open.php</strong></p>
<pre><code><html>
<body>
<div id="myDiv">Hello world.</div>
<script>
open("open1.php");
</script>
</body>
</html>
</code></pre>
<p><strong>open1.php</strong></p>
<pre><code><html>
<script>
open("open2.php");
</script>
</html>
</code></pre>
<p><strong>open2.php</strong></p>
<pre><code><html>
<script>
alert( opener.opener.document.getElementById('myDiv').innerText );
</script>
</html>
</code></pre>
|
Sum of odd numbers between 2 integers divisible by 7 <p>I am using Java and want to find the sum of all odd numbers between 0 and 100, that are divisible by 7.</p>
<p>I got this:</p>
<pre><code>public class odd7{
public static void main(String[] args)
{
int i = 1;
int a;
int b;
int sum = 0;
while(i <= 100)
{
a = i % 2;
b = i % 7;
if(a==1 && b==0)
{
sum = sum + i;
}
i = i + 1;
}
System.out.println(sum);
}
}
</code></pre>
<p>It's working perfectly fine, but I think it can be more shorter.</p>
<p>Thanks!</p>
| <p>Starting at <code>7</code> and incrementing by <code>14</code> (to keep only the odd numbers):</p>
<pre><code>int sum = 0;
for(int i = 7; i <= 100; i += 14) {
sum += i;
}
System.out.println(sum);
</code></pre>
<p>(I understand it is kind of a hack but it is just a possible answer!)</p>
|
Servicestack - Authentication questions <p>I am currently fighting a bit with my custom <code>CredentialsAuthProvider</code> implementation. First it is important to say, that I am writing a WPF client as a reference for my API.</p>
<ol>
<li>A browser stores cookies and you can configure how to deal with them, e.g. delete when the browser is closed. On windows desktop you have Environment.SpecialFolder.Cookies where Windows stores cookies. But I could not find anything from ServiceStack. So does it not store anything on a Windows Desktop app? I saw there is a <code>client.CookieContainer</code> where I find three cookies after login.</li>
<li><p>Can I somehow add properties to this cookie during Authentication? If so how? Currently I use <code>AuthenticationResponse.Meta</code>Dictionary to transfer additional information:</p>
<pre><code>public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
{
var authResponse = (AuthenticateResponse)base.Authenticate(authService, session, request);
authResponse.Meta = new Dictionary<string, string>();
authResponse.Meta.Add("Test", "TestValue");
return authResponse;
}
</code></pre></li>
<li><p>And finally: Is an instance of my derived <code>CredentialsAuthProvider</code> class thread safe? In <code>TryAuthenticate(...)</code> I make a DB connection and retrieve an object which contains all information including hashed password etc. But I can only fill this information to the session object in <code>OnAuthenticated(....)</code> and/or overridden <code>Authenticate(...)</code>. If possible I do not want to make another DB call to retrieve the same object again. So is it safe to declare a member <code>user</code> fill it in <code>TryAuthenticate</code> and reuse it in other overwritten methods like so:</p>
<pre><code>public class BediCredentialsAuthProvider : CredentialsAuthProvider
{
private AppUser user = null;
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
{
var authResponse = (AuthenticateResponse)base.Authenticate(authService, session, request);
authResponse.Meta = new Dictionary<string, string>();
authResponse.Meta.Add("ValueA", user.ValueA);
// ... add more properties from user object
return authResponse;
}
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
AppUser user = null;
using (var session = NhSessionFactories.OpenSession(TopinConstants.TopInDbFactory))
{
using (var transaction = session.BeginTransaction())
{
try
{
var appUserRepo = new AccountManagementRepository(session);
user = appUserRepo.GetAppUser(userName); // get user from database using NHibernate
transaction.Commit();
session.Close();
}
catch (Exception ex)
{
Log.Error($"Error retrieving user {user} to authenticate. Error: {ex}");
throw;
}
}
}
// do some logic to test passed credentials and return true or false
}
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens,
Dictionary<string, string> authInfo)
{
session.DisplayName = user.DisplayName;
session.FirstName = user.Firstname;
session.LastName = user.Lastname;
session.Email = user.EmailAddress;
// etc.....
return base.OnAuthenticated(authService, session, tokens, authInfo);
}
}
</code></pre></li>
</ol>
| <p>You can populate ServiceStack Service Client Cookies just like you would a browser except it only retains permanent Session Ids where you'll need to authenticate with <code>RememberMe=true</code>, e.g:</p>
<pre><code>var response = client.Post(new Authenticate {
provider = "credentials",
UserName = ...,
Password = ...,
RememberMe = true,
});
</code></pre>
<p>Which will save the Authenticated User Session against the <code>ss-pid</code> permanent Cookie in the HttpWebRequest CookieContainer and gets sent on every subsequent request.</p>
<p>You can set your own Permanent Cookies in <code>OnAuthenticated</code> from <code>authService</code> with:</p>
<pre><code>var httpRes = authService.Request.Response;
httpRes.SetPermanentCookie(cookieName, cookieValue);
</code></pre>
<blockquote>
<p>Is an instance of my derived CredentialsAuthProvider class thread safe?</p>
</blockquote>
<p>No the same AuthProvider singleton instance is used to Authenticate each request so you can't maintain any stored variables on the instance itself and will need to remove:</p>
<pre><code>//private AppUser user = null; //Instance variables are not ThreadSafe
</code></pre>
<p>If you want to pass items and access them throughout the Request Pipeline you can store them in <code>IRequest.Items</code> Dictionary, e.g:</p>
<pre><code>authService.Request.Items["AppUser"] = user;
</code></pre>
|
Can't connect to mac in visual studio <p>I'm trying to connect to mac in visual studio.</p>
<p>I did every step and I also connected to the Xamarin account.</p>
<p>In the Xamarin Mac Agent it found the mac which means I did the steps.</p>
<p>So sharing preferences are correctly configured at mac.</p>
<p>But when I try to connect to mac, after entering username and password it shows the following error:</p>
<blockquote>
<p>Couldn't connect to MacBook.local. Please try again.</p>
</blockquote>
<p>I don't know how I can solve this problem.</p>
<p>Any help will be appreciated</p>
<p>Thanks in advance</p>
| <p>The Xamarin.iOS SDK and Xcode both need to be installed on the Mac you're trying to connect to. See <a href="https://developer.xamarin.com/guides/ios/getting_started/installation/windows/#System_Requirements" rel="nofollow">Installing Xamarin.iOS on Windows</a> and the step-by-step <a href="https://developer.xamarin.com/guides/ios/getting_started/installation/" rel="nofollow">installation guides</a>.</p>
<p>Once Xamarin is installed on both Mac and PC, you can check the log files for hints about any connectivity issues you may encounter.</p>
<ul>
<li>Mac â ~/Library/Logs/Xamarin-[MAJOR.MINOR]</li>
<li>Windows â %LOCALAPPDATA%\Xamarin\Logs</li>
</ul>
<p>You may also find the <a href="https://developer.xamarin.com/guides/ios/getting_started/installation/windows/connecting-to-mac/troubleshooting/" rel="nofollow">Connection Troubleshooting</a> and general <a href="https://developer.xamarin.com/guides/cross-platform/troubleshooting/questions/version-logs/" rel="nofollow">diagnostic info</a> guides helpful.</p>
|
How to use volume's button to zoom in/out text in textview <p>How to override and use volume buttons to zoom IN/OUT text inside in layout, similar as when you are writing/reading SMS ?</p>
| <p>Please check this solution.</p>
<pre><code>public class MainActivity extends AppCompatActivity {
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.OpenClose);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
float x = txt.getScaleX();
float y = txt.getScaleY();
txt.setScaleX(x - 1);
txt.setScaleY(y - 1);
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
float x = txt.getScaleX();
float y = txt.getScaleY();
txt.setScaleX(x + 1);
txt.setScaleY(y + 1);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
}
</code></pre>
|
Keyboard input of array of bits <p>I want to make a program that applies some logic gates (<code>AND</code>, <code>OR</code>, <code>XOR</code>) to elements of two arrays of 1 and 0. But I am having problems with the user input of these arrays. I don't know how to make the arrays store only 1 and 0, for example if I type 5 I want the program to tell me it's neither 0 nor 1 and start over, I tried something but it's not working:</p>
<pre><code>int v1[50],v2[50],i,j,n;
printf("Number of elements in arrays : ");
scanf("%d",&n);
printf("Introduce elements of first array :\n");
for(i=0;i<n;i++)
if(v1[i] == 0 || v1[i]==1)
scanf("%d",&v1[i]);
else (i'll make it a function and I want it to repeat if the elements given are not 1 and 0)
for(i=0;i<n;i++)
printf("%d",v1[i]);
</code></pre>
| <p>In your first for loop, where you are reading the input, you should read the input first, and then decide whether you want to have the user try the input again. So, the first few lines of your for loop should look like this:</p>
<pre><code>for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
if (!(v1[i] == 0 || v1[i] == 1)) {
printf("Invalid input, please try again");
//Ask for another input, but do not advance i
}
}
</code></pre>
<p>This code will tell the user if they inputted a bad character, but it will not update the array correctly. To do this, all you need to do is decrement i once. This will make the previous "bad" value in <code>v1</code> get overwritten.</p>
<pre><code>for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
if (!(v1[i] == 0 || v1[i] == 1)) {
printf("Invalid input, please try again");
i--;
}
}
</code></pre>
<p>We are not done, however. In your original code, you defined v1 to be an array of 50 elements. What if someone wants to input 51 elements? You would eventually end up with accessing an array index that is out of bounds, which could lead to some very big issues. So, you need to do some dynamic memory allocation using <code>malloc</code></p>
<pre><code>int *v1, i, n;
printf("How many elements will be in the bit array? ");
scanf("%d", &n);
//Dynamically allocate enough memory for an integer array of length n
v1 = (int *) malloc(n * sizeof(int));
</code></pre>
<p>You can read more about malloc <a href="https://en.wikipedia.org/wiki/C_dynamic_memory_allocation" rel="nofollow">here</a>.
So, the whole code would look like this:</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
int main() {
int *v1, i, n;
printf("How many elements will be in the bit array? ");
scanf("%d", &n);
//Dynamically allocate enough memory for an integer array of length n
v1 = (int *) malloc(n * sizeof(int));
printf("Input the elements of the first array (separated by newlines):\n");
for (i = 0; i < n; i++) {
scanf("%d", &v1[i]);
if (!(v1[i] == 0 || v1[i] == 1)) {
printf("Invalid input, please try again");
i--;
}
}
</code></pre>
|
Swift: Understanding NSLock deadlock <p>Seeing this message in our logs using <code>NSLock</code>:</p>
<pre><code>*** -[NSLock lock]: deadlock (<NSLock: 0x6100000cbec0> '(null)')
*** Break on _NSLockError() to debug.
</code></pre>
<p>Does this mean that the application has encountered a fatal error and will stop working? Or is this handled in some kind of 'graceful' fashion?</p>
| <p>A deadlock, by definition, means that the thread in question cannot proceed. Swift doesn't "handle" the deadlock, but is merely informing you that this occurred.</p>
<p>How this deadlock manifests itself in your app depends upon what the code associated with that thread was doing. But, obviously, whatever it was, it will never complete and the resources for that thread will never be recovered. And if this deadlock took place on the main thread, the app will freeze.</p>
<p>Bottom line, the purpose of this message is not to tell you that the deadlock was handled, but to the contrary, to tell you that it can't be handled, and, so therefore, that it's incumbent upon you to fix the code to eliminate this problem.</p>
|
Periodically update database <p>Given a database (currently <strong>MongoDB</strong>) is there a proper and efficient way to periodically update <strong>all</strong> the values of the database?.</p>
<p>Let's say I want certain values to decrease by 1 every second or so, and to get notified when those values reach 0 in my app. I would like to avoid (if possible) updating them manually from my app iterating over all the elements as it could get pretty inefficient to query and update all the database every second.</p>
<p>I'm interested in answers for other databases apart from mongo</p>
<p>Thanks</p>
| <p>MongoDB don't have notification if something happen on the server (example, a Trigger). Even more you can't create this type of logic (decrease the time until is 0 second) also because i don't see benefit to have into the Database the "seconds left".</p>
<p>If you are making a kind of "eBay" where an Item has a "time to live" before became invalidate then you can resolve it with MongoDB with <strong>findOneAndUpdate</strong> or <strong>updateMany</strong>.</p>
|
Android Instrumented Test Database magically becomes read-only in @Before <p>I have been working through some exercises to learn android. The sample project I put together runs fine. But, when I run all of the Instrumented Tests together, the tests for my content provider fail because the database is read-only when deletes are issued to the database. When I run the test class separately, the tests pass with flying colors. My <code>ContentProvider</code> test looks like so:</p>
<pre><code>public class TestProvider {
public static final String LOG_TAG = TestProvider.class.getSimpleName();
public void deleteAllRecordsFromProvider() {
InstrumentationRegistry.getTargetContext()
.getContentResolver().delete(
WeatherEntry.CONTENT_URI,
null,
null
);
InstrumentationRegistry.getTargetContext()
.getContentResolver().delete(
LocationEntry.CONTENT_URI,
null,
null
);
Cursor cursor = InstrumentationRegistry.getTargetContext()
.getContentResolver().query(
WeatherEntry.CONTENT_URI,
null,
null,
null,
null
);
assertEquals("Error: Records not deleted from Weather table during delete", 0, cursor.getCount());
cursor.close();
cursor = InstrumentationRegistry.getTargetContext()
.getContentResolver().query(
LocationEntry.CONTENT_URI,
null,
null,
null,
null
);
assertEquals("Error: Records not deleted from Location table during delete", 0, cursor.getCount());
cursor.close();
}
@Before
public void setUp() throws Exception {
deleteAllRecordsFromProvider();
}
@After
public void after() {
InstrumentationRegistry.getTargetContext()
.getContentResolver()
.acquireContentProviderClient(WeatherEntry.CONTENT_URI)
.getLocalContentProvider()
.shutdown();
}
@Test
public void testProviderRegistry() {
PackageManager pm = InstrumentationRegistry.getTargetContext().getPackageManager();
// We define the component name based on the package name from the context and the
// WeatherProvider class.
ComponentName componentName = new ComponentName(InstrumentationRegistry.getTargetContext().getPackageName(),
WeatherProvider.class.getName());
try {
// Fetch the provider info using the component name from the PackageManager
// This throws an exception if the provider isn't registered.
ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0);
// Make sure that the registered authority matches the authority from the Contract.
assertEquals("Error: WeatherProvider registered with authority: " + providerInfo.authority +
" instead of authority: " + WeatherContract.CONTENT_AUTHORITY,
providerInfo.authority, WeatherContract.CONTENT_AUTHORITY);
} catch (PackageManager.NameNotFoundException e) {
// I guess the provider isn't registered correctly.
assertTrue("Error: WeatherProvider not registered at " + InstrumentationRegistry.getTargetContext().getPackageName(),
false);
}
}
@Test
public void testGetType() {
// content://com.example.android.sunshine.app/weather/
String type = InstrumentationRegistry.getTargetContext()
.getContentResolver()
.getType(WeatherEntry.CONTENT_URI);
// vnd.android.cursor.dir/com.example.android.sunshine.app/weather
assertEquals("Error: the WeatherEntry CONTENT_URI should return WeatherEntry.CONTENT_TYPE",
WeatherEntry.CONTENT_TYPE, type);
String testLocation = "94074";
// content://com.example.android.sunshine.app/weather/94074
type = InstrumentationRegistry.getTargetContext().getContentResolver().getType(
WeatherEntry.buildWeatherLocation(testLocation));
// vnd.android.cursor.dir/com.example.android.sunshine.app/weather
assertEquals("Error: the WeatherEntry CONTENT_URI with location should return WeatherEntry.CONTENT_TYPE",
WeatherEntry.CONTENT_TYPE, type);
long testDate = 1419120000L; // December 21st, 2014
// content://com.example.android.sunshine.app/weather/94074/20140612
type = InstrumentationRegistry.getTargetContext().getContentResolver().getType(
WeatherEntry.buildWeatherLocationWithDate(testLocation, testDate));
// vnd.android.cursor.item/com.example.android.sunshine.app/weather/1419120000
assertEquals("Error: the WeatherEntry CONTENT_URI with location and date should return WeatherEntry.CONTENT_ITEM_TYPE",
WeatherEntry.CONTENT_ITEM_TYPE, type);
// content://com.example.android.sunshine.app/location/
type = InstrumentationRegistry.getTargetContext().getContentResolver().getType(LocationEntry.CONTENT_URI);
// vnd.android.cursor.dir/com.example.android.sunshine.app/location
assertEquals("Error: the LocationEntry CONTENT_URI should return LocationEntry.CONTENT_TYPE",
LocationEntry.CONTENT_TYPE, type);
}
@Test
public void testBasicWeatherQuery() {
// insert our test records into the database
WeatherDbHelper dbHelper = new WeatherDbHelper(InstrumentationRegistry.getTargetContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
long locationRowId = TestUtilities.insertNorthPoleLocationValues(InstrumentationRegistry.getTargetContext());
// Fantastic. Now that we have a location, add some weather!
ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId);
long weatherRowId = db.insert(WeatherEntry.TABLE_NAME, null, weatherValues);
assertTrue("Unable to Insert WeatherEntry into the Database", weatherRowId != -1);
// Test the basic content provider query
Cursor weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
WeatherEntry.CONTENT_URI,
null,
null,
null,
null
);
// Make sure we get the correct cursor out of the database
TestUtilities.validateCursor("testBasicWeatherQuery", weatherCursor, weatherValues);
weatherCursor.close();
}
@Test
public void testBasicLocationQueries() {
// insert our test records into the database
WeatherDbHelper dbHelper = new WeatherDbHelper(InstrumentationRegistry.getTargetContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
long locationRowId = TestUtilities.insertNorthPoleLocationValues(InstrumentationRegistry.getTargetContext());
// Test the basic content provider query
Cursor locationCursor = InstrumentationRegistry.getTargetContext()
.getContentResolver()
.query(
LocationEntry.CONTENT_URI,
null,
null,
null,
null
);
// Make sure we get the correct cursor out of the database
TestUtilities.validateCursor("testBasicLocationQueries, location query", locationCursor, testValues);
// Has the NotificationUri been set correctly? --- we can only test this easily against API
// level 19 or greater because getNotificationUri was added in API level 19.
if ( Build.VERSION.SDK_INT >= 19 ) {
assertEquals("Error: Location Query did not properly set NotificationUri",
locationCursor.getNotificationUri(), LocationEntry.CONTENT_URI);
}
locationCursor.close();
}
@Test
public void testUpdateLocation() {
// Create a new map of values, where column names are the keys
ContentValues values = TestUtilities.createNorthPoleLocationValues();
Uri locationUri = InstrumentationRegistry.getTargetContext().getContentResolver().
insert(LocationEntry.CONTENT_URI, values);
long locationRowId = ContentUris.parseId(locationUri);
// Verify we got a row back.
assertTrue(locationRowId != -1);
Log.d(LOG_TAG, "New row id: " + locationRowId);
ContentValues updatedValues = new ContentValues(values);
updatedValues.put(LocationEntry._ID, locationRowId);
updatedValues.put(LocationEntry.COLUMN_CITY_NAME, "Santa's Village");
// Create a cursor with observer to make sure that the content provider is notifying
// the observers as expected
Cursor locationCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(LocationEntry.CONTENT_URI, null, null, null, null);
TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver();
locationCursor.registerContentObserver(tco);
int count = InstrumentationRegistry.getTargetContext().getContentResolver().update(
LocationEntry.CONTENT_URI, updatedValues, LocationEntry._ID + "= ?",
new String[]{Long.toString(locationRowId)});
assertEquals(count, 1);
// Test to make sure our observer is called. If not, we throw an assertion.
//
// Students: If your code is failing here, it means that your content provider
// isn't calling getContext().getContentResolver().notifyChange(uri, null);
tco.waitForNotificationOrFail();
locationCursor.unregisterContentObserver(tco);
locationCursor.close();
// A cursor is your primary interface to the query results.
Cursor cursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
LocationEntry.CONTENT_URI,
null, // projection
LocationEntry._ID + " = " + locationRowId,
null, // Values for the "where" clause
null // sort order
);
TestUtilities.validateCursor("testUpdateLocation. Error validating location entry update.",
cursor, updatedValues);
cursor.close();
}
@Test
public void testInsertReadProvider() {
ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
// Register a content observer for our insert. This time, directly with the content resolver
TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver();
InstrumentationRegistry.getTargetContext().getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, tco);
Uri locationUri = InstrumentationRegistry.getTargetContext().getContentResolver().insert(LocationEntry.CONTENT_URI, testValues);
// Did our content observer get called? Students: If this fails, your insert location
// isn't calling getContext().getContentResolver().notifyChange(uri, null);
tco.waitForNotificationOrFail();
InstrumentationRegistry.getTargetContext().getContentResolver().unregisterContentObserver(tco);
long locationRowId = ContentUris.parseId(locationUri);
// Verify we got a row back.
assertTrue(locationRowId != -1);
// Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made
// the round trip.
// A cursor is your primary interface to the query results.
Cursor cursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
LocationEntry.CONTENT_URI,
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating LocationEntry.",
cursor, testValues);
cursor.close();
// Fantastic. Now that we have a location, add some weather!
ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId);
// The TestContentObserver is a one-shot class
tco = TestUtilities.getTestContentObserver();
InstrumentationRegistry.getTargetContext().getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, tco);
Uri weatherInsertUri = InstrumentationRegistry.getTargetContext().getContentResolver()
.insert(WeatherEntry.CONTENT_URI, weatherValues);
assertTrue(weatherInsertUri != null);
// Did our content observer get called? Students: If this fails, your insert weather
// in your ContentProvider isn't calling
// getContext().getContentResolver().notifyChange(uri, null);
tco.waitForNotificationOrFail();
InstrumentationRegistry.getTargetContext().getContentResolver().unregisterContentObserver(tco);
// A cursor is your primary interface to the query results.
Cursor weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
WeatherEntry.CONTENT_URI, // Table to Query
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // columns to group by
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating WeatherEntry insert.",
weatherCursor, weatherValues);
// Add the location values in with the weather data so that we can make
// sure that the join worked and we actually get all the values back
weatherValues.putAll(testValues);
weatherCursor.close();
// Get the joined Weather and Location data
weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
WeatherEntry.buildWeatherLocation(TestUtilities.TEST_LOCATION),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data.",
weatherCursor, weatherValues);
weatherCursor.close();
// Get the joined Weather and Location data with a start date
weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
WeatherEntry.buildWeatherLocationWithStartDate(
TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data with start date.",
weatherCursor, weatherValues);
weatherCursor.close();
// Get the joined Weather data for a specific date
weatherCursor = InstrumentationRegistry.getTargetContext().getContentResolver().query(
WeatherEntry.buildWeatherLocationWithDate(TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE),
null,
null,
null,
null
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location data for a specific date.",
weatherCursor, weatherValues);
weatherCursor.close();
}
@Test
public void testDeleteRecords() {
testInsertReadProvider();
// Register a content observer for our location delete.
TestUtilities.TestContentObserver locationObserver = TestUtilities.getTestContentObserver();
InstrumentationRegistry.getTargetContext().getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, locationObserver);
// Register a content observer for our weather delete.
TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();
InstrumentationRegistry.getTargetContext().getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver);
deleteAllRecordsFromProvider();
// Students: If either of these fail, you most-likely are not calling the
// getContext().getContentResolver().notifyChange(uri, null); in the ContentProvider
// delete. (only if the insertReadProvider is succeeding)
locationObserver.waitForNotificationOrFail();
weatherObserver.waitForNotificationOrFail();
InstrumentationRegistry.getTargetContext().getContentResolver().unregisterContentObserver(locationObserver);
InstrumentationRegistry.getTargetContext().getContentResolver().unregisterContentObserver(weatherObserver);
}
static private final int BULK_INSERT_RECORDS_TO_INSERT = 10;
static ContentValues[] createBulkInsertWeatherValues(long locationRowId) {
long currentTestDate = TestUtilities.TEST_DATE;
long millisecondsInADay = 1000 * 60 * 60 * 24;
ContentValues[] returnContentValues = new ContentValues[BULK_INSERT_RECORDS_TO_INSERT];
for (int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, currentTestDate += millisecondsInADay) {
ContentValues weatherValues = new ContentValues();
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationRowId);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, currentTestDate);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, 1.1);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, 1.2 + 0.01 * (float) i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, 1.3 - 0.01 * (float) i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, 75 + i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, 65 - i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, "Asteroids");
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, 5.5 + 0.2 * (float) i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, 321);
returnContentValues[i] = weatherValues;
}
return returnContentValues;
}
</code></pre>
<p>I have one other test that uses the <code>InstrumentationRegistry</code>:</p>
<pre><code>public class TestFetchWeatherTask {
static final String ADD_LOCATION_SETTING = "Sunnydale, CA";
static final String ADD_LOCATION_CITY = "Sunnydale";
static final Double ADD_LOCATION_LAT = 34.425833;
static final Double ADD_LOCATION_LON = -119.714167;
@Test
public void testAddLocation() {
// start from a clean state
InstrumentationRegistry.getTargetContext()
.getContentResolver()
.delete(WeatherContract.LocationEntry.CONTENT_URI,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
new String[]{ADD_LOCATION_SETTING});
FetchWeatherTask fwt = new FetchWeatherTask(InstrumentationRegistry.getTargetContext(), null);
long locationId = fwt.addLocation(ADD_LOCATION_SETTING, ADD_LOCATION_CITY,
ADD_LOCATION_LAT, ADD_LOCATION_LON);
// does addLocation return a valid record ID?
assertFalse("Error: addLocation returned an invalid ID on insert", locationId == -1);
// test all this twice
for ( int i = 0; i < 2; i++ ) {
// does the ID point to our location?
Cursor locationCursor = InstrumentationRegistry.getTargetContext()
.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
new String[]{
WeatherContract.LocationEntry._ID,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
WeatherContract.LocationEntry.COLUMN_CITY_NAME,
WeatherContract.LocationEntry.COLUMN_COORD_LAT,
WeatherContract.LocationEntry.COLUMN_COORD_LONG
},
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
new String[]{ADD_LOCATION_SETTING},
null);
// these match the indices of the projection
if (locationCursor.moveToFirst()) {
assertEquals("Error: the queried value of locationId does not match the returned value" +
"from addLocation", locationCursor.getLong(0), locationId);
assertEquals("Error: the queried value of location setting is incorrect",
locationCursor.getString(1), ADD_LOCATION_SETTING);
assertEquals("Error: the queried value of location city is incorrect",
locationCursor.getString(2), ADD_LOCATION_CITY);
assertEquals("Error: the queried value of latitude is incorrect",
Double.valueOf(locationCursor.getDouble(3)), ADD_LOCATION_LAT);
assertEquals("Error: the queried value of longitude is incorrect",
Double.valueOf(locationCursor.getDouble(4)), ADD_LOCATION_LON);
} else {
fail("Error: the id you used to query returned an empty cursor");
}
// there should be no more records
assertFalse("Error: there should be only one record returned from a location query",
locationCursor.moveToNext());
// add the location again
long newLocationId = fwt.addLocation(ADD_LOCATION_SETTING, ADD_LOCATION_CITY,
ADD_LOCATION_LAT, ADD_LOCATION_LON);
assertEquals("Error: inserting a location again should return the same ID",
locationId, newLocationId);
locationCursor.close();
}
// reset our state back to normal
InstrumentationRegistry.getTargetContext()
.getContentResolver()
.delete(WeatherContract.LocationEntry.CONTENT_URI,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
new String[]{ADD_LOCATION_SETTING});
InstrumentationRegistry.getTargetContext()
.getContentResolver()
.acquireContentProviderClient(WeatherContract.LocationEntry.CONTENT_URI)
.getLocalContentProvider()
.shutdown();
}
}
</code></pre>
<p>If I comment out this test, the <code>TestProvider</code> class passes. If I don't, all of the <code>TestProvider</code> tests fail with the same error:</p>
<blockquote>
<p>I/TestRunner: android.database.sqlite.SQLiteReadOnlyDatabaseException:
attempt to write a readonly database (code 1032)</p>
</blockquote>
<p>Can anyone help me figure out what is going on with my tests? Why is my database magically becoming read-only? I have googled around with no luck.</p>
| <p>To test a ContentProvider you should create a test that extends <a href="https://developer.android.com/reference/android/test/ProviderTestCase2.html" rel="nofollow">ProviderTestCase2</a>, add the <code>@RunWith(AndroidJUnit4.class)</code> annotation at the beginning of the test class definition, specify the test runner as <code>AndroidJUnitRunner</code> and annotate every test with <code>@Test</code>.</p>
<p>Then, inject the <code>Context</code></p>
<pre><code>@Override
protected void setUp() throws Exception {
setContext(InstrumentationRegistry.getTargetContext());
super.setUp();
}
</code></pre>
<p>and run your tests from Studio.</p>
<p>You can learn more in this <a href="https://developer.android.com/training/testing/integration-testing/content-provider-testing.html" rel="nofollow">lesson</a>.</p>
|
IndexError: list index of range. Python 3 <p>I was just trying to create a Matrix filled with zeros, like the function of numpy.</p>
<p>But it continues to give me that error. Here's the code:</p>
<pre><code>def zeros(a,b):
for i in range(a):
for j in range(b):
R[i][j]=0
return R
</code></pre>
<p>I tried with a=3 and b=2, so it would give me a 3x2 matrix filled with zeros. It is a part of the program to multiply matrix</p>
<p>I'm new in this whole programming world, thanks for the help.</p>
| <p>You could do that:</p>
<pre><code>>>> def zeros(a,b):
... return [[0 for _ in range(a)] for _ in range(b)]
...
>>> zeros(3,2)
[[0, 0, 0], [0, 0, 0]]
</code></pre>
<p>Or something more close to your code:</p>
<pre><code>def zeros(a,b):
R = []
l = [0]*a
for _ in range(b):
R.append(l)
return R
</code></pre>
|
How to properly crop an image to fit imageview <p>How do i crop an image that i use picasso with to properly fit the layouts parent width and a fixed height of e.g. 500 for both pictures taken in landscape mode and portrait mode. They may be scaled down or up, but without too great effect on the quality. A bit like how instagram fits their pictures in the scrolling view like squares. I need all pictures to fit the layouts width and a certain height. </p>
<p>Thanks in advance.</p>
<p>This is my code:</p>
<pre><code>if(item.getTitle().equals("Add Picture")){
verifyStoragePermissions(MainActivity.this);
Intent loadPicture = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(loadPicture, RESULT_LOAD_IMAGE);
}
</code></pre>
<p>And</p>
<pre><code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
ImageView imageView = (ImageView) findViewById(R.id.loadPictureImageView);
mlinearLayout = (LinearLayout) findViewById(R.id.imageScrollLayout);
int width = mlinearLayout.getWidth();
//Picasso.with(this).load(selectedImage).resize(width, 500).centerCrop().into(imageView);
//Picasso.with(this).load(selectedImage).resize(width, 500).centerInside().into(imageView);
Picasso.with(this).load(selectedImage).fit().into(imageView);
}
}
</code></pre>
<p>And my xml layout and imageview:</p>
<pre><code><LinearLayout
android:id="@+id/imageScrollLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="vertical"
android:layout_below="@+id/profile_layout">
<ImageView
android:layout_width="match_parent"
android:layout_height="400dp"
android:id="@+id/loadPictureImageView"
android:elevation="10dp" />
</LinearLayout>
</code></pre>
| <p>Use the <code>scaleType</code> attr through xml on the <code>ImageView</code> or use Picasso's built in image manipulation methods for determining scale and size. A good tutorial can be found <a href="https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit" rel="nofollow">here</a>.</p>
|
Vector of Generic Structs in Rust <p>I am creating an entity component system in Rust, and I would like to be able to store a <code>Vec</code> of components for each different <code>Component</code> type:</p>
<pre><code>pub trait Component {}
struct ComponentList<T: Component> {
components: Vec<T>,
}
</code></pre>
<p>Is it possible to create a collection of these <code>ComponentList</code>s?</p>
<pre><code>struct ComponentManager {
component_lists: Vec<ComponentList<_>>, // This does not work
}
</code></pre>
<p>This is intended to make it faster to retrieve a list of a certain <code>Component</code> type, as all instances of a certain type of component will be in the same <code>ComponentList</code>.</p>
| <p>Create a trait that each <code>ComponentList<T></code> will implement but that will hide that <code>T</code>. In that trait, define any methods you need to operate on the component list (you will not be able to use <code>T</code>, of course, you'll have to use trait objects like <code>&Component</code>).</p>
<pre><code>trait AnyComponentList {
// Add any necessary methods here
}
impl<T: Component> AnyComponentList for ComponentList<T> {
// Implement methods here
}
struct ComponentManager {
component_lists: Vec<Box<AnyComponentList>>,
}
</code></pre>
<hr>
<p>If you would like to have efficient lookup of a <code>ComponentList<T></code> based on <code>T</code> from the <code>ComponentManager</code>, you might want to look into <a href="https://crates.io/crates/anymap" rel="nofollow"><code>anymap</code></a> or <a href="https://crates.io/crates/typemap" rel="nofollow"><code>typemap</code></a> instead. <code>anymap</code> provides a simple map keyed by the type (i.e. you use a type <code>T</code> as the key and store/retrieve a value of type <code>T</code>). <code>typemap</code> generalizes <code>anymap</code> by associated keys of type <code>K</code> with values of type <code>K::Value</code>.</p>
|
Trying to compute payroll in java <p>I have to figure out if gross pay is between "so and so" it's "this" tax percentage, etc. I thought I was doing alright, but it keeps outputting every single tax answer as one answer if I enter a high number for hours worked... like this "Deductions are 275.0165.0770.0000000000001".</p>
<p>Am I also doing this an extremely long way because I'm overthinking?
Thanks so much for any help!</p>
<pre><code>import java.util.Scanner;
public class prob2
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
double range = (168);
System.out.println("Enter the number of hours worked in a week:");
double hours = in.nextDouble();
System.out.println("Enter rate per hour:");
double rate = in.nextDouble();
double overtimeHours = hours - 40;
double overtimePay = (overtimeHours * rate) * 1.5;
double basePay = (hours - overtimeHours) * rate;
double grossPay = basePay + overtimePay;
double socialSecurity = .1 * grossPay;
double medical = .06 * grossPay;
if (overtimeHours < 0 )
{
System.out.println("Number of overtime hours are " + 0);
}
else
{
System.out.println("Number of overtime hours are " + overtimeHours);
}
if (overtimeHours < 0 )
{
System.out.println("Base pay is " + hours * rate);
}
else
{
System.out.println("Base pay is " + basePay);
}
if (overtimeHours < 0 )
{
System.out.println("Overtime pay is " + 0);
}
else
{
System.out.println("Overtime pay is " + overtimePay);
}
if (grossPay < 0 )
{
System.out.println("Gross pay is " + hours * rate);
}
else
{
System.out.println("Gross pay is " + grossPay);
}
if (grossPay > 0 && grossPay < 43)
{
System.out.println("Deductions are " + socialSecurity + medical);
}
else
if (43.01 < grossPay && grossPay < 218.00)
{
System.out.println("Deductions are " + socialSecurity + medical + (.10 * grossPay));
}
else
if (218.01 < grossPay && grossPay < 753.00)
{
System.out.println("Deductions are " + socialSecurity + medical + (.15 * grossPay));
}
else
if (grossPay > 0 && 753.01 < grossPay && grossPay < 1762.00)
{
System.out.println("Deductions are " + socialSecurity + medical + (.25 * grossPay));
}
else
if (1762.01 < grossPay && grossPay < 3627.00)
{
System.out.println("Deductions are " + socialSecurity + medical + (.28 * grossPay));
}
}
}
</code></pre>
| <p>Please wrap your sum into parenthesis:</p>
<pre><code>System.out.println("Deductions are " + (socialSecurity + medical));
</code></pre>
<p>In this case it will create sum at first then concatenate result to string, otherwise it will concat socialSecurity then medical one by one.</p>
<p>The same rule is right for similar cases in your code.</p>
|
Python abundant, deficient, or perfect number <pre><code>def classify(numb):
i=1
j=1
sum=0
for i in range(numb):
for j in range(numb):
if (i*j==numb):
sum=sum+i
sum=sum+j
if sum>numb:
print("The value",numb,"is an abundant number.")
elif sum<numb:
print("The value",numb,"is a deficient number.")
else:
print("The value",numb,"is a perfect number.")
break
return "perfect"
</code></pre>
<p>The code takes a number(numb) and classifies it as an abundant, deficient or perfect number. My output is screwy and only works for certain numbers. I assume it's indentation or the break that I am using incorrectly. Help would be greatly appreciated. </p>
| <p>I would highly recommend u to create a one function which creates the proper divisor of given N, and after that, the job would be easy.</p>
<pre><code>def get_divs(n):
return [i for i in range(1, n) if n % i == 0]
def classify(num):
divs_sum = sum(get_divs(num))
if divs_sum > num:
print('{} is abundant number'.format(num))
elif divs_sum < num:
print('{} is deficient number'.format(num))
elif divs_sum == num:
print('{} is perfect number'.format(num))
</code></pre>
|
API to Database? <p>Please presume that I do not know anything about any of the things I will be mentioning because I really do not.</p>
<hr>
<p>Most OpenData sites have the possibility of exporting the presented file either in for example .csv or .json formats (<a href="http://opendata.brussels.be/explore/dataset/associations-clubs-sportifs/export/?start=0%3C/url" rel="nofollow">Example</a>). They also always have an API tab (<a href="http://opendata.brussels.be/explore/dataset/associations-clubs-sportifs/api/?start=0" rel="nofollow">Example API</a>).</p>
<p>I presume using the API would mean that if the data is updated you would receive the change whereas exporting it as .csv would mean the content will not be changed anymore.</p>
<p>My questions is: how does one use this API code to display the same table one would get when exporting a .csv file.</p>
<p>Would you use a database to extract this information? What kind of database and how do you link the API to the database?</p>
| <blockquote>
<p>I presume using the API would mean that if the data is updated you
would receive the change whereas exporting it as .csv would mean the
content will not be changed anymore.</p>
</blockquote>
<p>You are correct in the sense that, if you download the csv to your computer, that csv file won't be updated any more.<br>
An API is something you would call - in this case, you can call the API, saying "Hey, do you have the latest data on xxx?", and you will be given back the latest information about what you have asked. This does not mean though, that this site will notify you when there's a new update - you will have to keep calling the API (every hour, every day etc) to see if there are any changes.</p>
<blockquote>
<p>My questions is: how does one use this API code to display the same
table one would get when exporting a .csv file.</p>
</blockquote>
<p>You would:</p>
<ol>
<li>Call the API from a server code, or a cloud service</li>
<li>Let the server code or cloud service decipher (or "Parse") the response</li>
<li>Use the deciphered response to create a table made out of HTML, or to place it into a database</li>
</ol>
<blockquote>
<p>Would you use a database to extract this information? What kind of
database and how do you link the API to the database?</p>
</blockquote>
<p>You wouldn't necessarily need a database to extract information, although a database would be nice to place the final data inside.<br>
You would first need some sort of way to "call the REST API". There are many ways to do this - using Shell Script, using Python, using Excel VBA etc.<br>
I understand this is hard to visualize, so here is an example of step 1, where you can retrieve information.<br>
Try placing in the below URL (taken from the site you showed us) in your address bar of your Chrome browser, and hit enter
<a href="http://opendata.brussels.be/api/records/1.0/search/?dataset=associations-clubs-sportifs" rel="nofollow">http://opendata.brussels.be/api/records/1.0/search/?dataset=associations-clubs-sportifs</a></p>
<p>See how it gives back a lot of text with many brackets and commas? You've basically asked the site to give you some data, and this is the response they gave back (different browsers work differently - IE asks you to download the response as a .json file). You've basically called an API. </p>
<p>To see this data more cleanly, open your developer tools of your Chrome browser, and enter the following JavaScript code</p>
<pre><code>var url = 'http://opendata.brussels.be/api/records/1.0/search/?dataset=associations-clubs-sportifs';
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function() {
if (xhr.status === 200) {
// success
console.log(JSON.parse(xhr.responseText));
} else {
// error
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
</code></pre>
<p>When you hit enter, a response will come back, stating "Object". If you click through the arrows, you can see this is a cleaner version of the data we just saw - more human readable.</p>
<p><a href="https://i.stack.imgur.com/56hcU.gif" rel="nofollow"><img src="https://i.stack.imgur.com/56hcU.gif" alt="enter image description here"></a></p>
<p>In this case, I used JavaScript to retrieve the data, but you can use whatever code you want. You could proceed to use JavaScript to decipher the data, manipulate it, and push it into a database. </p>
<p><a href="https://www.kintone.com/" rel="nofollow">kintone</a> is an online cloud database where you can customize it to run JavaScript codes, and have it store the data in their database, so you'll have the data stored online like in the below image. This is just one example of a database you can use.</p>
<p><a href="https://i.stack.imgur.com/WYv5W.png" rel="nofollow"><img src="https://i.stack.imgur.com/WYv5W.png" alt="enter image description here"></a></p>
<p>There are other cloud services which allow you to connect API end points of different services with each other, like IFTTT and Zapier, but I'm not sure if they connect with open data.</p>
|
Arduino - 5 questions for real Wire.write() and Wire.read() explanation <p>I Googled this a lot, and it seems that I am not the only one having problems with really understanding Wire.write() and Wire.read(). Being novice, I almost never use libraries that are already written by somebody, I try to create my class for module in order to truly understand how this module works and to learn how to manipulate with it. I've read few books and too many tutorials, but I could summarise these in two:
a) all tutorials are just showing the very basics of how to use these methods and b) they don't actually explain the steps, like everything is totally self explanatory. Call me stupid, but I have the feeling like somebody told me that 1 + 1 = 2, and then gave me some polynomial equation to solve :(<br>
All book examples and almost all tutorials look like this imaginary example:</p>
<pre><code>Wire.beginTransmission(Module_Address); //Use this to start transmission
Wire.write(0); // go to first register
Wire.endTransmission(); // end this
</code></pre>
<p>//To read </p>
<pre><code>Wire.requestFrom(Module_Address, 3); //Read three registers
Wire.read(); //Read first register
Wire.read(); //Read second register
Wire.read(); //Read third register
</code></pre>
<p>And that's it about reading.
When it comes to writing, it's even worse:</p>
<pre><code>Wire.beginTransmission(Module_Address); //Use this to start transmission
Wire.write(0); // go to first register
Wire.write(something); //Write to first register
Wire.write(something); //write to second register
Wire.endTransmission(); // end this
</code></pre>
<p>So far, working with ANY module I got, it was NEVER that easy. Usually, every register has more than one "option" inside. For example, lets say that imaginary module has First read register like this: </p>
<p>ADDRESS | BIT 7 |Â BIT 6 | BIT 5 |Â BIT 4 | BIT 3 |Â BIT 2 | BIT 1 | BIT 0<br>
data Byte1 | mute .| option2.........|.....................option3.......................</p>
<p>To read only option 3, I would use this code:</p>
<pre><code>Wire.beginTransmission(module_address);
Wire.write(0);
Wire.endTransmission();
Wire.requestFrom(module_address, 1);
byte readings = Wire.read() & 0x1F; //0x1F is hexadecimal of binary 0001111 for option 3 in register 1
</code></pre>
<p>QUESTION 1<br>
What does this '&' after Wire.read() REALLY means? (I know that it points to option within register, but I do not really understand this, why is it there) </p>
<p>QUESTION 2<br>
Why the previous problem isn't written anywhere? So many tutorials, so many books, but I "discovered" it by accident when I tried to figure out how one library was working.</p>
<p>QUESTION 3<br>
Imagine that hypothetical module has third register in write mode looking like this:</p>
<p>ADDRESS | BIT 7 |Â BIT 6 | BIT 5 |Â BIT 4 | BIT 3 |Â BIT 2 | BIT 1 | BIT 0<br>
data Byte3 | write flag.......| option2.........|......................option3........ </p>
<p>How to write flag without affecting option 2 and option 3? Or in other words, how to write to register 3's write flag? If I take 11000000 could affect because maybe I do not know what exactly option 2 and 3 do, or I do not wish to interfere with default setup. </p>
<p>QUESTION 4<br>
Certain modules have to be written in binary-coded decimal. Let's say, that you have a timer and you wish to set 17 seconds for countdown to 0.And to do that, you need to write number 17 to register one, but number should be binary-coded decimal. 17 as binary-coded is: 0001 0111. But when you do this: </p>
<pre><code>Wire.beginTransmission(module_address);
Wire.write(0);
Wire.write(00010111);
Wire.endTransmission();
</code></pre>
<p>You get different number, 13 or 10 (can't recall what number, I know it was wrong).
However, when doing this conversion: 17/10*16 + 17%10 it writes correct number 17.
Yes, I also accidentally found this out. BUT, where is this equation from? I searched (obviously wrong) as much as I could, but there was nothing about it. So, how did somebody come with this equation? </p>
<p>QUESTION 5<br>
Probably a dumb off-topic question, BUT:<br>
should Arduino library be written in a way that others could find it difficult to figure out the idea behind it? In other words, to figure out what the developer was exactly doing? I remember that one person used a lot of messy code to read something from sensor and then formula to convert it from binary-coded decimal to print it to Serial Monitor, while the same thing could be done with simply<br>
Serial.print(read_byte, HEX);<br>
It's not that I am smarter (or better) than them, I just don't understand why somebody would write a complex code when there is no(really) need for that.</p>
<p>Thanks a lot for any help :)</p>
| <p>Questions 1. - 4.: Are all covered by <a href="http://www.avrfreaks.net/forum/tut-c-bit-manipulation-aka-programming-101?page=all" rel="nofollow">Bit Manipulation tutorial</a> on <a href="http://www.avrfreaks.net/" rel="nofollow">AVRFreaks</a> forum <a href="http://www.avrfreaks.net/?taxonomy_forums_tid=636&read_status=All&contibutor_status=All" rel="nofollow">Tutorials</a>. So in short:</p>
<ul>
<li>1) The <code>&</code> is used for bit masking in this case.</li>
<li>2) If you look for "Bit manipulation" then there are loads of Tutorials.</li>
<li>3) It's possible by Bit manipulation. How? For in memory variable just use bit masking. To clear two bits: <code>var &= 0b00111111</code> to set two bits: <code>var |= 0b11000000</code>. If you don't have register value, you have to Read & Modify & Write it back. If you can't read the value (for example it's internal address like for eeproms) you have to have this value in memory anyways.</li>
<li>4) In C++ numbers starting by zero are in Octal base. If you want binary, you have to use 0b00010111. For the HEX base you have to use 0xFF. This is not explicitly mentioned in that tutorial, but both are used here.</li>
<li>5) It should be as clear as possible. But for the begginers without good knowlege of C++ it's hard anyway. For me is most difficult to read the code without indentation or even worst with bad indentation, bad variable names. The libraries are usually written by advanced users, so it's not so hard to understand with some background like knowing the datasheet for used MCUs and so on.</li>
</ul>
<p>BTW: wrong comments are also bad for understanding:</p>
<pre><code>//0x1F is hexadecimal of binary 0001111 for option 3 in register 1
</code></pre>
<p>The value <code>0x1F</code> is definitely not <code>0001111</code> in binary but <code>00011111</code> (or better: <code>0b00011111</code>)</p>
|
Conditional Segue while passing data? <p>I'm trying to make the segue from viewcontroller to 2ndviewcontroller only when my condition is met. I've connected the segue from the button in viewcontroller to the 2ndviewcontroller. So far I have:</p>
<pre><code>@IBAction func switchView(_ sender: AnyObject) {
// if a and b's textfields aren't empty
if(!(a.text?.isEmpty)! && !(b.text?.isEmpty)!) {
a1 = a.text!;
b1 = b.text!;
}else{
// do something
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if(identifier == "2ndviewcontroller") {
if(!(a.text?.isEmpty)! && !(b.text?.isEmpty)!) {
return true
}
}
return false
}
</code></pre>
<p>With this, I've been able to make the segue ONLY when a and b's textfields are not empty. That's exactly what I want but I also want to pass data from viewcontroller to 2ndviewcontroller as well. </p>
<pre><code>func prepForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "2ndviewcontroller" {
let 2ndviewcontroller = segue.destination as! 2ndviewcontroller
2ndviewcontroller.c = a
}
}
}
</code></pre>
<p>I used the code above to pass data from viewcontroller to 2ndviewcontroller. Problem is I don't know how to combine them to both pass data, AND only make the segue when condition is met. When I have both functions, the bool function executes correctly, but prepForSegue does not pass data. When I comment out the bool function, prepForSegue passes the data, but I'm cannot apply a condition for making the segue.</p>
<p>Edit: fixed by using prepareForSegue method provided in the comments below.</p>
| <p>As discussed in the comments, the method name should be <code>prepareForSegue</code>, not <code>prepForSegue</code>.</p>
|
Always load entity for ApplicationUser (.NET MVC, Identity) <p>I am having problems loading a entity that I have assigned to the ApplicationUser in my .NET core MVC application.</p>
<p>I have added one of my entities to the user class, see code below:</p>
<pre><code>public class ApplicationUser : IdentityUser
{
public int? AzureBlobResourceId { get; set; }
[ForeignKey("AzureBlobResourceId")]
public AzureBlobResource AzureBlobResource { get; set; }
}
</code></pre>
<p>Ideally I want the AzureBlobResource object to be loaded when retrieving the user from the UserManager</p>
<pre><code>private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
</code></pre>
<p>Unfortunately though the AzureBlobResource object always is null, even when the AzureBlobResourceId has a value.</p>
<p>What am I missing here?</p>
<p>Thanks, Nikolai</p>
| <p>You need to implement your userstore</p>
<pre><code>public class ApplicationUser : IdentityUser {
public int? AzureBlobResourceId { get; set; }
[ForeignKey("AzureBlobResourceId")]
public AzureBlobResource AzureBlobResource { get; set; }
}
public class MyAppUserStore : UserStore<ApplicationUser>
{
public MyAppUserStore(DbContext context, IdentityErrorDescriber describer = null) : base(context, describer)
{
}
public override async Task<ApplicationUser> FindByIdAsync(string userId, CancellationToken cancellationToken = new CancellationToken())
{
return await Context.Set<ApplicationUser>().Include(p => p.AzureBlobResource).FirstOrDefaultAsync(u => u.Id == userId, cancellationToken: cancellationToken);
}
}
</code></pre>
<p>And in Sturtup.cs add </p>
<pre><code>ervices.AddIdentity<ApplicationUser, IdentityRole>()
.AddUserStore<MyAppUserStore >()
.AddUserManager<UserManager<ApplicationUser>>()
.AddDefaultTokenProviders();
</code></pre>
|
Shaman.EPPlus + ASP.NET Core MVC - Part already exist exception <p>I am using <a href="https://www.nuget.org/packages/Shaman.EPPlus/" rel="nofollow">Shaman.EPPlus</a>, a version of EPPlus that should be compatible with ASP.NET Core MVC.
I am trying to export a collection of object as xlxs file.
The code looks like this:</p>
<pre><code>foreach(var client in clientsToExport)
{
clientList.Add(new object[] { "FirstName", client.FirstName });
}
MemoryStream stream = new MemoryStream();
using (ExcelPackage pck = new ExcelPackage(stream))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Clients");
ws.Cells["A1"].LoadFromArrays(clientList);
pck.Save();
Response.Clear();
Response.Headers.Add("content-disposition", "attachment; filename=Clients.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var bytes = pck.GetAsByteArray();
Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
</code></pre>
<p>It seems that an exception containing the message "Par already exist" is thrown when GetAsByteArray method is called.</p>
<blockquote>
<p>at OfficeOpenXml.Packaging.ZipPackage.CreatePart(Uri partUri, String contentType, CompressionLevel compressionLevel)<br>
at OfficeOpenXml.ExcelWorkbook.Save()<br>
at OfficeOpenXml.ExcelPackage.GetAsByteArray(Boolean save)</p>
</blockquote>
<p>Do you know what could I check?</p>
| <p>The problem are these line:</p>
<pre><code>pck.Save();
....
var bytes = pck.GetAsByteArray();
</code></pre>
<p>Both calls will cause the package to be closed by Epplus. You do not need the <code>.Save</code> call since that will automatically be called by <code>.GetAsByteArray</code> anyway so simply remove the first line.</p>
|
how to stop a function from running code until a condition is met <p>Here is a simplified version of my code. <code>function1()</code> has to check something on the internet. It has to do it in the background of the app(I cannot change that), which allows the rest of the code to run while it checks the internet. This function can take several seconds to complete. I cannot put the log at the end of function 1 because it needs to run whether function1 is successful or not, but only after it is done trying. How can I achieve this without using a timer?</p>
<pre><code>if (condition) {
if (condition2) {
function1();
}
Log.i("Info", "This should not appear until function1 completes or fails");
}
</code></pre>
| <p>Don't constantly check; this is called <em>busy waiting</em> and is inefficient, especially on mobile (since the device can't go into low-power mode). Instead, use an <code>AsyncCallback</code> to run your <code>function1</code> and put the log message in the callback.</p>
|
Check if elements in an array are inside of another array <p>So If I have these two arrays:</p>
<p><code>int array1[] = {1, 2 ,3};</code></p>
<p><code>int array2[] = {1, 2, 3, 4, 5};</code></p>
<p>How do I check if <code>1, 2 and 3</code> from array1 are in array2? `</p>
<p>Thanks in advance.</p>
| <p><a href="http://en.cppreference.com/w/cpp/algorithm/includes" rel="nofollow"><code>std::includes</code></a>:</p>
<pre><code>if (std::includes(std::begin(array2), std::end(array2),
std::begin(array1), std::end(array1)) {
// array2 includes array1
}
</code></pre>
<p>This requires the arrays are sorted, which yours are. Also, if they are sorted with some custom comparator, you must pass that to <code>std::includes</code> as well.</p>
<p>It is worth pointing out that I use your arrays the "wrong" way round; the algorithm expects its first range to be the larger one.</p>
|
fitEllipse returns ellipses that is twice as big as the actual contour <p><a href="https://i.stack.imgur.com/OcEsY.png" rel="nofollow"><img src="https://i.stack.imgur.com/OcEsY.png" alt="enter image description here"></a></p>
<p>As you can see the contour is much smaller than the fitted ellipse. Below is the relevant code I use to generate the ellipse. Can someone tell me what I am doing wrong? Thank you.</p>
<pre><code>cv2.drawContours(orig, contour,-1, (0, 255, 0),3) #draw the green contour on image "orig"
(center, size, angle) = cv2.fitEllipse(contour) #get best fit Ellipse from contour
cv2.ellipse(grey_scale,(int(round(center[0])),int(round(center[1]))),(int(round(size[0])),int(round(size[1]))),int(round(angle)),0,360,(0,255,0),1) # draw ellipse on image "grey_scale" with the statistics gathered from second line
</code></pre>
| <p>The <a href="http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html#ellipse" rel="nofollow">draw function</a> expects half of the size:</p>
<blockquote>
<p><strong>axes</strong> â Half of the size of the ellipse main axes.</p>
</blockquote>
<p>A simpler way of doing this is:</p>
<pre><code>cv2.drawContours(orig, contour,-1, (0,255,0), 3)
my_ellipse = cv2.fitEllipse(contour)
cv2.ellipse(grey_scale, my_ellipse, (0,255,0), 1)
</code></pre>
|
How to validate PayPal data with IPN when using non-hosted PayPal button <p>I am rather new to PHP and adding payment gateways</p>
<p>However, I want to learn and am having a go at a small shop with a Paypal buy now button which is linked to a PHP cookies cart</p>
<p>It is working fine and shows a list of the items in the cart, however I am worried it is not secure enough and someone could change the amounts or add their email address so that they receive funds</p>
<p>I would like to integrate the instant payment notification (IPN) : <a href="https://www.paypal.com/uk/cgi-bin/webscr?cmd=p/acc/ipn-info-outside" rel="nofollow">https://www.paypal.com/uk/cgi-bin/webscr?cmd=p/acc/ipn-info-outside</a></p>
<p>Do I need to do much more than follow the above instructions and make an IPN in the merchant account?</p>
<p>I am a bit confused about what the POST code means and how to integrate it into my button code</p>
<p>Please could someone explain what I need to change in my Paypal button code below so that I can make the payment system secure? I keep breaking it</p>
<pre><code><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<!--input type="hidden" name="item_name_1" value="Something Cool">
<input type="hidden" name="quantity_1" value="5">
<input type="hidden" name="amount_1" value="1"-->
<?php
$i = 0;
foreach (json_decode($_COOKIE['cart_items_cookie']) as $key => $value) {
$i++;
echo '<input type="hidden" name="item_name_'.$i.'" value="'.$value->name.'">';
echo '<input type="hidden" name="amount_'.$i.'" value="'.$value->price.'">';
}
?>
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="me@mysite.com">
<input type="hidden" name="item_name" value="Order#21874">
<input type="hidden" name="currency_code" value="GBP">
<!--<input type="hidden" name="amount" value="<?php //echo $_GET['total'];? > "> -->
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHosted">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal â The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</code></pre>
<p>Any help or point in the right direction much appreciated!</p>
| <p>The best thing to do would be to use the <a href="https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECReference/" rel="nofollow">Express Checkout API</a> instead of Payments Standard (HTML forms). This requires more programming and working with API calls, however, I have a <a href="https://www.angelleye.com/product/paypal-sdk-php/" rel="nofollow">PayPal PHP class library</a> you can use to make all of the calls very quick and easy for you. </p>
<p>Express Checkout completely hides everything about the payment and it has a lot more features available to it than Standard does.</p>
<p>If you want to stick with Standard, you can build a hosted button by creating the button from within your PayPal account, and make sure to select the option to "Save the button at PayPal." That is what makes it hosted.</p>
<p>Then you'll still get HTML to paste into your site where you want the payment button to show up, but it will only have a few lines, and one of those lines will show a "hosted_button_id". </p>
<p>This secures the button from tampering like you mentioned, but it limits customization you can do with your checkout in general.</p>
|
Google javascript API: catching HTTP errors <p><a href="http://stackoverflow.com/users/26406/abraham">Abraham</a>'s answer to <a href="http://stackoverflow.com/questions/29562774/google-calendar-api-backend-error-code-503">Google Calendar API : "Backend Error" code 503</a> exactly describes my situation. I get 503s at random places when looping through code that creates or deletes calendar entries. </p>
<p>However, I can't figure out how to follow the advice that he cites from Google, which is to catch the error and retry the transaction using exponential back off.</p>
<p>The code below is a loop that puts 8 new events into my calendar. It randomly experiences 503 errors, which are thrown from the Google API instead of my own code. Many times it works without an error. </p>
<p>The Google API code runs asynchronously from my loop so none of the Google actions actually execute until my Loop is done. The Try-catch surrounding my code doesn't fire when the asynch code throws a 503. I can't put a "catch" into the callback function without a try, and that would narrow the scope of the catch to exclude Google's code.</p>
<p>Any suggestions? </p>
<pre><code>/* Special date string format for all-day Google Calendar events.
Time zone independent.
*/
Date.prototype.yyyy_mm_dd = function() {
var yyyy= this.getFullYear().toString();
var mm = (this.getMonth()+101).toString().slice(-2); //get leading 0
var dd = (this.getDate()+100).toString().slice(-2);
return yyyy+'-'+mm+'-'+dd;
}
var fastevent = {
'summary': 'Fast',
'organizer': {
'self': true,
'displayName': 'Wes Rishel',
'email': 'wrishel@gmail.com'},
'start': {'date': 'zzzz'}, // filled in for each instance
'end': {'date': 'zzzz'},
'colorId': '11',
}
function addFastEvents() {
try {
var eventDate = calendar.getLastFastDate() || new Date;
for (var eventCount = 0; eventCount < 8; eventCount++) {
// advance to next Tuesday or Friday
eventDate=eventDate.addDays(
[2, 1, 3, 2, 1, 4, 3][eventDate.getDay()]
);
fastevent.start.date = eventDate.yyyy_mm_dd();
fastevent.end.date = fastevent.start.date;
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': fastevent
});
request.execute(function(fastevent) {});
calendar.getPage(eventDate);
calendar.setCellStyle(eventDate, 'fastingweekdaydata');
} // for
} catch(e) {
p(e.message, e.name)
}
}
</code></pre>
| <p>Exponential backoff is a fancy way of saying that at each attempt, you increase the wait time exponentially, for a certain number of times before giving up the request.</p>
<p><a href="https://developers.google.com/drive/v3/web/handle-errors#exponential-backoff" rel="nofollow">Implementing exponential backoff</a></p>
<blockquote>
<p>Exponential backoff is a standard error handling strategy for network
applications in which the client periodically retries a failed request
over an increasing amount of time. If a high volume of requests or
heavy network traffic causes the server to return errors, exponential
backoff may be a good strategy for handling those errors</p>
</blockquote>
<p>Here's a <a href="https://jsfiddle.net/pajtai/pLka0ow9/" rel="nofollow">demo code in JS</a> that might give you an idea:</p>
<pre><code>console.log = consoleLog;
exponentialBackoff(sometimesFails, 10, 100, function(result) {
console.log('the result is',result);
});
// A function that keeps trying, "toTry" until it returns true or has
// tried "max" number of times. First retry has a delay of "delay".
// "callback" is called upon success.
function exponentialBackoff(toTry, max, delay, callback) {
console.log('max',max,'next delay',delay);
var result = toTry();
if (result) {
callback(result);
} else {
if (max > 0) {
setTimeout(function() {
exponentialBackoff(toTry, --max, delay * 2, callback);
}, delay);
} else {
console.log('we give up');
}
}
}
function sometimesFails() {
var percentFail = 0.8;
return Math.random() >= 0.8;
}
function consoleLog() {
var args = [].slice.apply(arguments);
document.querySelector('#result').innerHTML += '\n' + args.join(' - ');
}
</code></pre>
|
Bootstrap MYSQL PHP - Send Modal Content <p>I have data I'm displaying in a table, using bootstrap. For each of those I'm wanting to do a modal, on this you would confirm you want to send an email.</p>
<p>This is the link they would click:</p>
<pre><code><a data-toggle="modal" data-target="#email-'.$row['id'].'">Resend Email</a>
</code></pre>
<p>The modal is on another page, and I've included this within the while for the MYSQL data using:</p>
<pre><code>include 'modal/modal-resend-email.php';
</code></pre>
<p>On this page I then load the modal using:</p>
<pre><code><div id="email-<?php echo $row['id'];?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p><?php echo $row['number_tenants']; echo $row['full_name_one'];?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</code></pre>
<p>For each of the buttons that load you can click them and it will open a modal, the problem is it only ever shows data from the very first row, am I doing something wrong, or is there a better way to do this?</p>
<p>Thanks!</p>
| <p>I think your <code><a data-toggle="modal" data-target="#email-'.$row['id'].'">Resend Email</a></code> anchor needs to have a class. </p>
<p>I would write it in a simpler manner than you: <code><a href="" class="modal-open">Resend Email</a></code>.</p>
<p>Then, you need to somehow, pass your data from db, to each modal. So I'll want to update the above anchor, to have the db data too. So I'd add custom html attributes to store whatever data comes from db. I'll use a simple case, when you'd want to update just a name. So you should adapt this example for your needs. </p>
<p><code><a href="" class="modal-open" data-id="<?php echo $row['id'];?>" data-name="<?php echo $row['name'];?>">Resend Email</a></code>.</p>
<p>Pretending this is your modal:</p>
<pre><code><div class="modal fade" tabindex="-1" role="dialog" id="modal-update">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form action="update.php" method="POST" id="update-form">
<div class="form-group">
<label for="modal-update-id">ID</label>
<input type="number" id="modal-update-id" class="form-control modal-update-id" disabled="disabled">
</div>
<div class="form-group">
<label for="modal-update-name">Name</label>
<input type="text" id="modal-update-name" class="form-control modal-update-name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="modal-save">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</code></pre>
<p>Then I'd put javascript to get the job done. First, when the user clicks one of the <code>Resend Email</code> links, you need to get the id and the name stored in that particular link (through <code>data-id</code> and <code>data-name</code> attributes) and populate the modal fields with them. So:</p>
<pre><code>var updateId = 0;
var updateName = '';
$('.modal-open').click(function(e){ // when one of the links are clicked..
e.preventDefault();//prevent the default behaviour of the link
updateId = $(this).attr('data-id');//grab the data-id attr value
updateName = $(this).attr('data-name');//grab the data-name attr value
$('.modal-update-id').val(updateId);//populate the id field of the modal with that grabbed value
$('.modal-update-name').val(updateName);//populate the name field of the modal with that grabbed value
$('#modal-update').modal();//show the modal
});
$('#modal-save').click(function(e){//when the user clicks the Save changes button...
e.preventDefault();
$.ajax({
method: $('#update-form').attr('method'),//grab the modal's form method
url: $('#update-form').attr('action'),//grab the modal's form action
data: { id:updateId, name:$('.modal-update-name').val(), age:$('.modal-update-age').val() },//grab the user's new data from the modal
cache:false
}).done(function(msg){
document.location.reload();//reload the page to see the changes
$('#modal-update').modal('hide');//hide the modal
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus + ' ' + errorThrown);
});
});
</code></pre>
<p>I guess this should do the trick.</p>
|
Google Sheets Formula to Extract and Convert Currency from ⬠or £ to USD <p>I'm trying to do the following:</p>
<ol>
<li>Check the cell for <code>N/A</code> or <code>No</code>; if it has either of these then it should output <code>N/A</code> or <code>No</code></li>
<li>Check the cell for either <code>£</code> or <code>â¬</code> or <code>Yes</code>; If it has one of these then it would continue to step 3. If it has <code>$</code> then it should repeat the same input as the output.</li>
<li>Extract currency from cell using: <code>REGEXEXTRACT(A1, "\$\d+")</code> or <code>REGEXEXTRACT(A1, "\£\d+")</code> (I assume that's the best way)</li>
<li>Convert it to $ USD using <code>GoogleFinance("CURRENCY:EURUSD")</code> or <code>GoogleFinance("CURRENCY:GBPUSD")</code></li>
<li>Output the original cell but replacing the extracted currency from step 3 with the output from step 4.</li>
</ol>
<h3>Examples: (<strong>Original --> Output</strong>)</h3>
<ul>
<li><code>N/A</code> --> <code>N/A</code> </li>
<li><code>No</code> --> <code>No</code> </li>
<li><code>Alt</code> --> <code>Alt</code> </li>
<li><code>Yes</code> --> <code>Yes</code> </li>
<li><code>Yes £10</code> --> <code>Yes $12.19</code></li>
<li><code>Yes £10 per week</code> --> <code>Yes $12.19 per week</code></li>
<li><code>Yes â¬5 (Next)</code> --> <code>Yes $5.49 (Next)</code></li>
<li><code>Yes $5 22 EA</code> --> <code>Yes $5 22 EA</code></li>
<li><code>Yes £5 - £10</code> --> <code>Yes $5.49 - $12.19</code></li>
</ul>
<p>I am unable to get a working <code>IF</code> statement working, I could do this in normal code but can't work it out for spreadsheet formulas.</p>
<p>I've tried modifying @Rubén's answer lots of times to including the <code>N/A</code> as it's not the Sheets error, I also tried the same for making any USD inputs come out as USD (no changes) but I really can't get the hang of IF/OR/AND in Excel/Google Sheets.</p>
<pre><code>=ArrayFormula(
SUBSTITUTE(
A1,
OR(IF(A1="No","No",REGEXEXTRACT(A1, "[\£|\â¬]\d+")),IF(A1="N/A","N/A",REGEXEXTRACT(A1, "[\£|\â¬]\d+"))),
IF(
A1="No",
"No",
TEXT(
REGEXEXTRACT(A1, "[\£|\â¬](\d+)")*
IF(
"â¬"=REGEXEXTRACT(A1, "([\£|\â¬])\d+"),
GoogleFinance("CURRENCY:EURUSD"),
GoogleFinance("CURRENCY:GBPUSD")
),
"$###,###"
)
)
)
)
</code></pre>
<p>The above, I tried to add an OR() before the first IF statement to try and include <code>N/A</code> as an option, in the below I tried it as you can see below in various different ways (replace line 4 with this)</p>
<pre><code>IF(
OR(
A1="No",
"No",
REGEXEXTRACT(A1, "[\£|\â¬]\d+");
A1="No",
"No",
REGEXEXTRACT(A1, "[\£|\â¬]\d+")
)
)
</code></pre>
<p>But that doesn't work either. I thought using <code>;</code> was a way to separate the OR expressions but apparently not.</p>
<h1>Re: Rubén's latest code 16/10/2016</h1>
<p>I've modified it to =ArrayFormula(
IF(NOT(ISBLANK(A2)),</p>
<pre><code>IF(IFERROR(SEARCH("$",A2),0),A2,IF(A2="N/A","N/A",IF(A2="No","No",IF(A2="Alt","Alt",IF(A2="Yes","Yes",
SUBSTITUTE(
A2,
REGEXEXTRACT(A2, "[\£|\â¬]\d+"),
TEXT(
REGEXEXTRACT(A2, "[\£|\â¬](\d+)")
*
VLOOKUP(
REGEXEXTRACT(A2, "([\£|\â¬])\d+"),
{
{"£";"â¬"},
{GoogleFinance("CURRENCY:GBPUSD");GoogleFinance("CURRENCY:EURUSD")}
},
2,0),
"$###,###"
)
)
)))))
,"")
)
</code></pre>
<p>This fixes:</p>
<ul>
<li>Blank cells no longer throw #N/A</li>
<li><code>Yes</code> only cells no longer throw #N/A</li>
<li>Added another text value <code>Alt</code></li>
<li>Changes the format of the currency to 0 decimal places rather than my original request of 2 decimal places.</li>
</ul>
<p>As you can see in the image below the two red cells aren't quite correct as I never thought of this scenario, the second of the two values is staying in it's input form and not being converted to USD.</p>
<p><a href="https://i.stack.imgur.com/yQLUV.png" rel="nofollow"><img src="https://i.stack.imgur.com/yQLUV.png" alt="enter image description here"></a></p>
| <h1>Direct answer</h1>
<p>Try</p>
<pre>
=ArrayFormula(
IF(IFERROR(SEARCH("$",A1:A6),0),A1:A6,IF(A1:A6="N/A","N/A",IF(A1:A6="No","No",
SUBSTITUTE(
A1:A6,
REGEXEXTRACT(A1:A6, "[\£|\â¬]\d+"),
TEXT(
REGEXEXTRACT(A1:A6, "[\£|\â¬](\d+)")
*
VLOOKUP(
REGEXEXTRACT(A1:A6, "([\£|\â¬])\d+"),
{
{"£";"â¬"},
{GoogleFinance("CURRENCY:GBPUSD");GoogleFinance("CURRENCY:EURUSD")}
},
2,0),
"$###,###.00"
)
)
)))
)
</pre>
<p>Result</p>
<pre>
+---+------------------+---------------------+
| | A | B |
+---+------------------+---------------------+
| 1 | N/A | N/A |
| 2 | No | No |
| 3 | Yes £10 | Yes $12.19 |
| 4 | Yes £10 per week | Yes $12.19 per week |
| 5 | Yes â¬5 (Next) | Yes $5.49 (Next) |
+---+------------------+---------------------+
</pre>
<h1>Explanation</h1>
<h2>OR function</h2>
<p>Instead or using OR function, the above formula use nested IF functions.</p>
<h2>REGEXTRACT</h2>
<p>Instead of using a REGEXEXTRACT function for each currency symbol, a regex OR operator was used. Example</p>
<pre><code>REGEXEXTRACT(A1:A6, "[\£|\â¬]\d+")
</code></pre>
<p>Three regular expressions were used, </p>
<ul>
<li>get currency symbol and the amount <code>[\£|\â¬]\d+</code></li>
<li>get the amount <code>[\£|\â¬](\d+)</code></li>
<li>get the currency symbol <code>[(\£|\â¬])\d+</code></li>
</ul>
<h2>Currency conversion</h2>
<p>Instead of using nested IF to handle currency conversion rates, VLOOKUP and array is used. This could be make easier to maintain the formula assuming that more currencies could be added in the future.</p>
|
How can I "generalize" what R uses as my x and y values in a plot <p>I have written an executable script in R that will simply plot a graph given an input file in a tab delimited format. However, the script I wrote is specific to a single file in terms of what to use as x and y. I want to have this script be able to plot whatever file I give it. All files I will be using for this script will be in the same format: Tab delimited with 4 headers with labels a, b, c, d. Labels b,c, and d have a different name for each file. My x values for the graph will be the values under header b and y values for the graph will be the values under header c. How can I plot a graph that will use whatever is under header b and c? </p>
<p>My script is posted below.</p>
<pre><code>#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
data = read.table((args[1]), header=TRUE, fill=TRUE, sep="\t")
attach (data)
jpeg(args[2])
plot (RPMb, RPMc)
dev.off()
</code></pre>
| <p>Instead of using <code>attach()</code> (which is almost never recommended), use data frame indexing to extract the relevant variables from your <code>data</code> variable.</p>
<pre><code>#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
data = read.table((args[1]), header=TRUE, fill=TRUE, sep="\t")
jpeg(args[2])
x <- names(data)[2]
y <- names(data)[3]
plot (data[[x]], data[[y]],xlab=x,ylab=y)
dev.off()
</code></pre>
<p>You could also just use <code>plot(data[,2],data[,3])</code> ...</p>
<p>A couple of other details/comments:</p>
<ul>
<li>it's generally best to avoid naming variables for built-in functions such as <code>data</code>. It will usually work, but occasionally it will bite you.</li>
<li>are you sure you want JPEG output? Either PNG or PDF are usually best for line graphs, depending on whether you need a raster or a vector format ...</li>
</ul>
|
Makefile findstring yields nonempty string even though the argument is not in the whitelist <p>I want my Makefile to require that an environment be specified, e.g.</p>
<pre><code>make ENV=beta all
</code></pre>
<p>My Makefile begins like this</p>
<pre><code>ifeq ($(findstring ${ENV}, dev beta prod),)
$(error ENV must be dev, beta, or prod (e.g. make ENV=dev))
endif
nop:
echo "Nothing done."$(findstring ${ENV}, dev beta prod)"#"
</code></pre>
<p>If I run</p>
<pre><code>make ENV=devx nop
</code></pre>
<p>I get this output</p>
<pre><code>Makefile:7: *** ENV must be dev, beta, or prod (e.g. make ENV=dev). Stop.
</code></pre>
<p>On the other hand</p>
<pre><code>make ENV=d nop
</code></pre>
<p>gives this output</p>
<pre><code>echo "Nothing done."d"#"
Nothing done.d#
</code></pre>
<p>This shows that <code>$(findstring...</code> is returning a non-empty string <a href="https://www.gnu.org/software/make/manual/html_node/Text-Functions.html" rel="nofollow">contrary to the documentation</a></p>
<p>What's the catch?</p>
| <p>The <code>findstring</code> function is finding an instance of "d"; the documentation is ambiguous, not incorrect. Use <code>filter</code> instead.</p>
|
Trying to push_back into a vector pointing to an abstract class <p>Compiling my code that contains this class:</p>
<pre><code>class Dessin
{
private:
vector<Figures*>T;
public:
void ajouteFigure(const Figures& f) const
{
for(auto element: T)
{
T.push_back(f);
}
}
};
</code></pre>
<p>yields an error:</p>
<blockquote>
<p>[Error] no matching function for call to
'std::vector::push_back(const Figures&) const'</p>
</blockquote>
<p>This is what I'm supposed to do in the main()</p>
<pre><code>Dessin s;
s.ajouteFigure(Cercle(1.1));
</code></pre>
<p>Why wouldn't this work?</p>
| <p>Assuming <code>Cercle</code> is a class name, you're trying to push a value where a pointer is expected. </p>
<p>To "fix" the error you should change your <code>ajouteFigure</code> prototype to accept <code>Figures</code> pointers and non-const <code>this</code>:</p>
<pre><code>void ajouteFigure(Figures* f)
</code></pre>
<p>Then you should call it passing a pointer to a <code>Figures</code> object, i.e. created with a <code>new</code> expression:</p>
<pre><code>s.ajouteFigure(new Cercle(1.1));
</code></pre>
<p>That being said, this code seems pointless. You're adding the pointer as many times as you have elements in the vector (which is always 0 in the example you provided).</p>
<p>Using raw pointers is also unadvised, you should use smart pointers like <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr" rel="nofollow"><code>std::unique_ptr</code></a>, although that would break the current code.</p>
<p>Consider this, less improper, example:</p>
<pre><code>class Dessin
{
private:
vector<unique_ptr<Figures>> T;
public:
void ajouteFigure(unique_ptr<Figures> f)
{
T.push_back(move(f)); // just once
}
};
</code></pre>
<p>and at the call site:</p>
<pre><code>Dessin s;
s.ajouteFigure(make_unique<Cercle>(1.1)); // C++â¥14
</code></pre>
<p>or, if you can't use C++14:</p>
<pre><code>Dessin s;
s.ajouteFigure(unique_ptr<Figures>(new Cercle{1.1}));
</code></pre>
|
Improving on chains of if/else statements <p>Given the discussion <a href="http://blog.demofox.org/2016/10/14/a-data-point-for-msvc-vs-clang-code-generation/" rel="nofollow">here</a>, which is roughly about getting the compiler to compute if/else at compile time...</p>
<pre><code>#include <initializer_list>
template<typename U, typename ... T>
bool one_of(U&& u, T && ... t)
{
bool match = false;
(void)std::initializer_list<bool>{ (match = match || u == t)... };
return match;
}
int main(int argc, char** argv)
{
return one_of(argc, 1, 2, 3, 4, 5);
}
</code></pre>
<p>I've been working in older C++ land for quite a while and am not as clued in on modern C++ as I'd like to be, so...</p>
<p>Is there a way to do the above with, for example, an array of strings that is known at compile time? I'd greatly prefer that it avoid loops. The above works fairly well for int/float types and generates 3 to 5 instructions in x86_64 for the example above.</p>
<p>In it's most simple form, I guess this question is about how to turn an array into a list of arguments for a templated function.</p>
<p>Edit: at the request of krzaq</p>
<p>What I'd like to see if the above but instead of <code>one_of( argc, 1, 2, 3, 4, 5 )</code> I'd like to have <code>one_of( argc, array_of_compiletime_ints )</code> and have it boiled down to similar code and have it work for things other than char/short/int/float/double.</p>
<p>If you look at any of the godbolt links, you'll see that it compiles down to very little code.</p>
| <p>Attempting to leverage the Turing completeness of the template system has been a thing since the early 90s :):)</p>
<p>But compilers usually courteously but adamantly, and wisely so, refuse to go too deep into template computation because it would imply extensive compile time spent extremely slowly evaluating something that could so easily be expressed as a way faster runtime computation :)</p>
|
GGPLOT: Printing Stacked Bar Chart & Line to File <p>I know that it might not look like it from this question, but I've actually been programming for over 20 years, but I'm new to R. I'm trying to move away from Excel and to automate creation of about 100 charts I currently do in Excel by hand. I've asked two previous questions about this: <a href="http://stackoverflow.com/questions/40064496/ggplot-only-printing-gray-boxes-to-file?noredirect=1#comment67403965_40064496">here</a> and <a href="http://stackoverflow.com/questions/40053861/plot-line-on-top-of-stacked-bar-chart-in-ggplot2?noredirect=1#comment67393259_40053861">here</a>. Those solutions work for those toy examples, but when I try the exact same code on my own full program, they behave very differently and I'm completely befuddled as to why. When I run the program below, the testplot.png file is just a plot of the line, without the stacked bar chart.</p>
<p>So here is my (full) code as cut down as I can make it. If anyone wants to critique my programming, go ahead. I know that the comments are light, but that's to try to shorten it for this post. Also, this does actually download the USDA PSD database which is about 20MB compressed and is 170MB uncompressed...sorry but I would <em>love</em> someone's help on this!</p>
<p>Edit, here are str() outputs of both 'full' data and 'toy' data. The toy data works, the full data doesn't.</p>
<pre><code>> str(melteddata)
Classes âdata.tableâ and 'data.frame': 18 obs. of 3 variables:
$ Year : int 1 2 3 4 5 6 1 2 3 4 ...
$ variable: Factor w/ 3 levels "stocks","exports",..: 1 1 1 1 1 1 2 2 2 2 ...
$ Qty : num 2 4 3 2 4 3 4 8 6 4 ...
- attr(*, ".internal.selfref")=<externalptr>
> str(SoySUHist)
Classes âdata.tableâ and 'data.frame': 159 obs. of 3 variables:
$ Year : int 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 ...
$ variable: Factor w/ 3 levels "Stocks","DomCons",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Qty : num 0.0297 0.0356 0.0901 0.1663 0.3268 ...
- attr(*, ".internal.selfref")=<externalptr>
> str(linedata)
Classes âdata.tableâ and 'data.frame': 6 obs. of 2 variables:
$ Year: int 1 2 3 4 5 6
$ Qty : num 15 16 15 16 15 16
- attr(*, ".internal.selfref")=<externalptr>
> str(SoyProd)
Classes âdata.tableâ and 'data.frame': 53 obs. of 2 variables:
$ Year: int 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 ...
$ Qty : num 701 846 928 976 1107 ...
- attr(*, ".internal.selfref")=<externalptr>
>
library(data.table)
library(ggplot2)
library(ggthemes)
library(plyr)
toyplot <- function(plotdata,linedata){
plotCExp <- ggplot(plotdata) +
geom_bar(aes(x=Year,y=Qty,factor=variable,fill=variable), stat="identity") +
geom_line(data=linedata, aes(x=Year,y=Qty)) # <---- comment out this line & the stack plot works
ggsave(plotCExp,filename = "ggsavetest.png", width=7, height=5, units="in")
}
convertto <- function(value,crop,unit='BU'){
if (unit=='BU' & ( crop=='WHEAT' | crop=='SOYBEANS')){
value = value * 36.7437
}
return(value)
}
# =====================================
# Download Data (Warning...large download!)
# =====================================
system("curl https://apps.fas.usda.gov/psdonline/download/psd_alldata_csv.zip | funzip > DATA/psd.csv")
tmp <- fread("DATA/psd.csv")
PSD = data.table(tmp)
rm(tmp)
setkey(PSD,Country_Code,Commodity_Code,Attribute_ID)
tmp=unique(PSD[,.(Commodity_Description,Attribute_Description,Commodity_Code,Attribute_ID)])
tmp[order(Commodity_Description)]
names(PSD)[names(PSD) == "Market_Year"] = "Year"
names(PSD)[names(PSD) == "Value"] = "Qty"
PSDCmdtyAtt = unique(PSD[,.(Commodity_Code,Attribute_ID)])
# Soybean Production, Consumpion, Stocks/Use
SoyStocks = PSD[list("US",2222000,176),.(Year,Qty)] # Ending Stocks
SoyExp = PSD[list("US",2222000,88),.(Year,Qty)] # Exports
SoyProd = PSD[list("US",2222000,28),.(Year,Qty)] # Total Production
SoyDmCons = PSD[list("US",2222000,125),.(Year,Qty)] # Total Dom Consumption
SoyStocks$Qty = convertto(SoyStocks$Qty,"SOYBEANS","BU")/1000
SoyExp$Qty = convertto(SoyExp$Qty,"SOYBEANS","BU")/1000
SoyProd$Qty = convertto(SoyProd$Qty,"SOYBEANS","BU")/1000
SoyDmCons$Qty = convertto(SoyDmCons$Qty,"SOYBEANS","BU")/1000
# Stocks/Use
SoySUPlot <- SoyExp
names(SoySUPlot)[names(SoySUPlot) == "Qty"] = "Exports"
SoySUPlot$DomCons = SoyDmCons$Qty
SoySUPlot$Stocks = SoyStocks$Qty
SoySUHist <- melt(SoySUPlot,id.vars="Year")
SoySUHist$Qty = SoySUHist$value/1000
SoySUHist$value <- NULL
SoySUPlot$StocksUse = 100*SoySUPlot$Stocks/(SoySUPlot$DomCons+SoySUPlot$Exports)
SoySUPlot$Production = SoyProd$Qty/1000
SoySUHist$variable <- factor(SoySUHist$variable, levels = rev(levels(SoySUHist$variable)))
SoySUHist = arrange(SoySUHist,variable)
toyplot(SoySUHist,SoyProd)
</code></pre>
| <p>All right, I'm feeling generous. Your example code contains a lot of fluff that should not be in a minimal reproducible example and your <code>system</code> call is not portable, but I had a look anyway. </p>
<p>The good news: Your code works as expected.</p>
<p>Let's plot only the bars:</p>
<pre><code>ggplot(SoySUHist) +
geom_bar(aes(x=Year,y=Qty,factor=variable,fill=variable), stat="identity")
</code></pre>
<p><a href="https://i.stack.imgur.com/WSeuJ.png" rel="nofollow"><img src="https://i.stack.imgur.com/WSeuJ.png" alt="plot 1"></a></p>
<p>Now only the lines:</p>
<pre><code>ggplot(SoySUHist) +
geom_line(data=SoyProd, aes(x=Year,y=Qty))
</code></pre>
<p><a href="https://i.stack.imgur.com/BXN7X.png" rel="nofollow"><img src="https://i.stack.imgur.com/BXN7X.png" alt="plot 2"></a></p>
<p>Now compare the scales of the y-axes. If you plot both together, the bars get plotted, but they are so small that you can't see them. You need to rescale:</p>
<pre><code>ggplot(SoySUHist) +
geom_bar(aes(x=Year,y=Qty,factor=variable,fill=variable), stat="identity") +
geom_line(data=SoyProd, aes(x=Year,y=Qty/1000))
</code></pre>
<p><a href="https://i.stack.imgur.com/cTjwB.png" rel="nofollow"><img src="https://i.stack.imgur.com/cTjwB.png" alt="plot 3"></a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.