This problem may also happen if you have a unit test project that has a different C++ version than the project you want to test.
Example:
Solution: change the Unit Test to C++17 as well.
The problem is in your "this" value. Timer function cannot access the "state" prop because run in a different context. I suggest you to do something like this:
...
startTimer = () => {
let interval = setInterval(this.timer.bind(this), 1000);
this.setState({ interval });
};
As you can see I've added a "bind" method to your timer function. This allows the timer, when called, to access the same "this" of your react component (This is the primary problem/improvement when working with javascript in general).
Another option is to use another arrow function:
startTimer = () => {
let interval = setInterval(() => this.timer(), 1000);
this.setState({ interval });
};
Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.
Sometimes using image = array(img).reshape(a,b,c,d)
will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is
np.expand_dims(img, axis=0)
It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.
I use and may advise the following solution (python3.6):
y = int(x + (x % (1 if x >= 0 else -1)))
It works fine for half-numbers (positives and negatives) and works even faster than int(round(x)):
round_methods = [lambda x: int(round(x)),
lambda x: int(x + (x % (1 if x >= 0 else -1))),
lambda x: np.rint(x).astype(int),
lambda x: int(proper_round(x))]
for rm in round_methods:
%timeit rm(112.5)
Out:
201 ns ± 3.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
159 ns ± 0.646 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
925 ns ± 7.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.18 µs ± 8.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
for rm in round_methods:
print(rm(112.4), rm(112.5), rm(112.6))
print(rm(-12.4), rm(-12.5), rm(-12.6))
print('=' * 11)
Out:
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
Here is my solution and it's also working, when element shows into the viewport
var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
var firEvent = false,
objectPosTop = $('.go-counterTeaser').offset().top;
//when element shows at bottom
var elementViewInBottom = objectPosTop - winHeight;
$(window).on('scroll', function() {
var currentPosition = $(document).scrollTop();
//when element position starting in viewport
if (currentPosition > elementViewInBottom && firEvent === false) {
firEvent = true;
animationCounter();
}
});
}
//counter function will animate by using external js also add seprator "."
function animationCounter(){
$('.numberBlock h2').each(function () {
var comma_separator_number_step = $.animateNumber.numberStepFactories.separator('.');
var counterValv = $(this).text();
$(this).animateNumber(
{
number: counterValv,
numberStep: comma_separator_number_step
}
);
});
}
https://jsfiddle.net/uosahmed/frLoxm34/9/
You may try this:
public static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12345");
System.out.println(toPrecision(a, 2));
}
private static BigDecimal toPrecision(BigDecimal dec, int precision) {
String plain = dec.movePointRight(precision).toPlainString();
return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}
OUTPUT:
10.12
You can't do this using forms the normal way. Instead, you want to use AJAX.
A sample function that will submit the data and alert the page response.
function submitForm() {
var http = new XMLHttpRequest();
http.open("POST", "<<whereverTheFormIsGoing>>", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
value = value.setScale(2, RoundingMode.CEILING)
simply don't close in
remove in.close()
from your code.
Python indexing starts at 0 (rather than 1), so your assignment "r[1,:] = r0" defines the second (i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.
Seems to me that the right formula should be:
n64 = 4 * (n / 3) + (n % 3 != 0 ? 4 : 0)
Add
"aaSorting": []
And check if default value is not null
only set sortable column then
if ($('#table').DataTable().order().length == 1) {
d.SortColumn = $('#table').DataTable().order()[0][0];
d.SortOrder = $('#table').DataTable().order()[0][1];
}
You can use the data attribute data-orderable="false"
.
<th data-orderable="false">Salary</th>
$(document).ready(function() {_x000D_
$('#example').DataTable()_x000D_
});
_x000D_
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>_x000D_
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>_x000D_
_x000D_
<table id="example" class="display" style="width:100%">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th>Position</th>_x000D_
<th>Office</th>_x000D_
<th>Age</th>_x000D_
<th>Start date</th>_x000D_
<th data-orderable="false">Salary</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Tiger Nixon</td>_x000D_
<td>System Architect</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>61</td>_x000D_
<td>2011/04/25</td>_x000D_
<td>$320,800</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Garrett Winters</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>63</td>_x000D_
<td>2011/07/25</td>_x000D_
<td>$170,750</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Ashton Cox</td>_x000D_
<td>Junior Technical Author</td>_x000D_
<td>San Francisco</td>_x000D_
<td>66</td>_x000D_
<td>2009/01/12</td>_x000D_
<td>$86,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Cedric Kelly</td>_x000D_
<td>Senior Javascript Developer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>22</td>_x000D_
<td>2012/03/29</td>_x000D_
<td>$433,060</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Airi Satou</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>33</td>_x000D_
<td>2008/11/28</td>_x000D_
<td>$162,700</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Brielle Williamson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>New York</td>_x000D_
<td>61</td>_x000D_
<td>2012/12/02</td>_x000D_
<td>$372,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Herrod Chandler</td>_x000D_
<td>Sales Assistant</td>_x000D_
<td>San Francisco</td>_x000D_
<td>59</td>_x000D_
<td>2012/08/06</td>_x000D_
<td>$137,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Rhona Davidson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>Tokyo</td>_x000D_
<td>55</td>_x000D_
<td>2010/10/14</td>_x000D_
<td>$327,900</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Colleen Hurst</td>_x000D_
<td>Javascript Developer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>39</td>_x000D_
<td>2009/09/15</td>_x000D_
<td>$205,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sonya Frost</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>23</td>_x000D_
<td>2008/12/13</td>_x000D_
<td>$103,600</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jena Gaines</td>_x000D_
<td>Office Manager</td>_x000D_
<td>London</td>_x000D_
<td>30</td>_x000D_
<td>2008/12/19</td>_x000D_
<td>$90,560</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Quinn Flynn</td>_x000D_
<td>Support Lead</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>22</td>_x000D_
<td>2013/03/03</td>_x000D_
<td>$342,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Charde Marshall</td>_x000D_
<td>Regional Director</td>_x000D_
<td>San Francisco</td>_x000D_
<td>36</td>_x000D_
<td>2008/10/16</td>_x000D_
<td>$470,600</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Haley Kennedy</td>_x000D_
<td>Senior Marketing Designer</td>_x000D_
<td>London</td>_x000D_
<td>43</td>_x000D_
<td>2012/12/18</td>_x000D_
<td>$313,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Tatyana Fitzpatrick</td>_x000D_
<td>Regional Director</td>_x000D_
<td>London</td>_x000D_
<td>19</td>_x000D_
<td>2010/03/17</td>_x000D_
<td>$385,750</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Michael Silva</td>_x000D_
<td>Marketing Designer</td>_x000D_
<td>London</td>_x000D_
<td>66</td>_x000D_
<td>2012/11/27</td>_x000D_
<td>$198,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Paul Byrd</td>_x000D_
<td>Chief Financial Officer (CFO)</td>_x000D_
<td>New York</td>_x000D_
<td>64</td>_x000D_
<td>2010/06/09</td>_x000D_
<td>$725,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Gloria Little</td>_x000D_
<td>Systems Administrator</td>_x000D_
<td>New York</td>_x000D_
<td>59</td>_x000D_
<td>2009/04/10</td>_x000D_
<td>$237,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Bradley Greer</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>London</td>_x000D_
<td>41</td>_x000D_
<td>2012/10/13</td>_x000D_
<td>$132,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Dai Rios</td>_x000D_
<td>Personnel Lead</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>35</td>_x000D_
<td>2012/09/26</td>_x000D_
<td>$217,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jenette Caldwell</td>_x000D_
<td>Development Lead</td>_x000D_
<td>New York</td>_x000D_
<td>30</td>_x000D_
<td>2011/09/03</td>_x000D_
<td>$345,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Yuri Berry</td>_x000D_
<td>Chief Marketing Officer (CMO)</td>_x000D_
<td>New York</td>_x000D_
<td>40</td>_x000D_
<td>2009/06/25</td>_x000D_
<td>$675,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Caesar Vance</td>_x000D_
<td>Pre-Sales Support</td>_x000D_
<td>New York</td>_x000D_
<td>21</td>_x000D_
<td>2011/12/12</td>_x000D_
<td>$106,450</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Doris Wilder</td>_x000D_
<td>Sales Assistant</td>_x000D_
<td>Sidney</td>_x000D_
<td>23</td>_x000D_
<td>2010/09/20</td>_x000D_
<td>$85,600</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Angelica Ramos</td>_x000D_
<td>Chief Executive Officer (CEO)</td>_x000D_
<td>London</td>_x000D_
<td>47</td>_x000D_
<td>2009/10/09</td>_x000D_
<td>$1,200,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Gavin Joyce</td>_x000D_
<td>Developer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>42</td>_x000D_
<td>2010/12/22</td>_x000D_
<td>$92,575</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jennifer Chang</td>_x000D_
<td>Regional Director</td>_x000D_
<td>Singapore</td>_x000D_
<td>28</td>_x000D_
<td>2010/11/14</td>_x000D_
<td>$357,650</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Brenden Wagner</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>28</td>_x000D_
<td>2011/06/07</td>_x000D_
<td>$206,850</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Fiona Green</td>_x000D_
<td>Chief Operating Officer (COO)</td>_x000D_
<td>San Francisco</td>_x000D_
<td>48</td>_x000D_
<td>2010/03/11</td>_x000D_
<td>$850,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Shou Itou</td>_x000D_
<td>Regional Marketing</td>_x000D_
<td>Tokyo</td>_x000D_
<td>20</td>_x000D_
<td>2011/08/14</td>_x000D_
<td>$163,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Michelle House</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>Sidney</td>_x000D_
<td>37</td>_x000D_
<td>2011/06/02</td>_x000D_
<td>$95,400</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Suki Burks</td>_x000D_
<td>Developer</td>_x000D_
<td>London</td>_x000D_
<td>53</td>_x000D_
<td>2009/10/22</td>_x000D_
<td>$114,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Prescott Bartlett</td>_x000D_
<td>Technical Author</td>_x000D_
<td>London</td>_x000D_
<td>27</td>_x000D_
<td>2011/05/07</td>_x000D_
<td>$145,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Gavin Cortez</td>_x000D_
<td>Team Leader</td>_x000D_
<td>San Francisco</td>_x000D_
<td>22</td>_x000D_
<td>2008/10/26</td>_x000D_
<td>$235,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Martena Mccray</td>_x000D_
<td>Post-Sales support</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>46</td>_x000D_
<td>2011/03/09</td>_x000D_
<td>$324,050</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Unity Butler</td>_x000D_
<td>Marketing Designer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>47</td>_x000D_
<td>2009/12/09</td>_x000D_
<td>$85,675</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Howard Hatfield</td>_x000D_
<td>Office Manager</td>_x000D_
<td>San Francisco</td>_x000D_
<td>51</td>_x000D_
<td>2008/12/16</td>_x000D_
<td>$164,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Hope Fuentes</td>_x000D_
<td>Secretary</td>_x000D_
<td>San Francisco</td>_x000D_
<td>41</td>_x000D_
<td>2010/02/12</td>_x000D_
<td>$109,850</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Vivian Harrell</td>_x000D_
<td>Financial Controller</td>_x000D_
<td>San Francisco</td>_x000D_
<td>62</td>_x000D_
<td>2009/02/14</td>_x000D_
<td>$452,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Timothy Mooney</td>_x000D_
<td>Office Manager</td>_x000D_
<td>London</td>_x000D_
<td>37</td>_x000D_
<td>2008/12/11</td>_x000D_
<td>$136,200</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jackson Bradshaw</td>_x000D_
<td>Director</td>_x000D_
<td>New York</td>_x000D_
<td>65</td>_x000D_
<td>2008/09/26</td>_x000D_
<td>$645,750</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Olivia Liang</td>_x000D_
<td>Support Engineer</td>_x000D_
<td>Singapore</td>_x000D_
<td>64</td>_x000D_
<td>2011/02/03</td>_x000D_
<td>$234,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Bruno Nash</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>London</td>_x000D_
<td>38</td>_x000D_
<td>2011/05/03</td>_x000D_
<td>$163,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sakura Yamamoto</td>_x000D_
<td>Support Engineer</td>_x000D_
<td>Tokyo</td>_x000D_
<td>37</td>_x000D_
<td>2009/08/19</td>_x000D_
<td>$139,575</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Thor Walton</td>_x000D_
<td>Developer</td>_x000D_
<td>New York</td>_x000D_
<td>61</td>_x000D_
<td>2013/08/11</td>_x000D_
<td>$98,540</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Finn Camacho</td>_x000D_
<td>Support Engineer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>47</td>_x000D_
<td>2009/07/07</td>_x000D_
<td>$87,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Serge Baldwin</td>_x000D_
<td>Data Coordinator</td>_x000D_
<td>Singapore</td>_x000D_
<td>64</td>_x000D_
<td>2012/04/09</td>_x000D_
<td>$138,575</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Zenaida Frank</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>New York</td>_x000D_
<td>63</td>_x000D_
<td>2010/01/04</td>_x000D_
<td>$125,250</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Zorita Serrano</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>56</td>_x000D_
<td>2012/06/01</td>_x000D_
<td>$115,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jennifer Acosta</td>_x000D_
<td>Junior Javascript Developer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>43</td>_x000D_
<td>2013/02/01</td>_x000D_
<td>$75,650</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Cara Stevens</td>_x000D_
<td>Sales Assistant</td>_x000D_
<td>New York</td>_x000D_
<td>46</td>_x000D_
<td>2011/12/06</td>_x000D_
<td>$145,600</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Hermione Butler</td>_x000D_
<td>Regional Director</td>_x000D_
<td>London</td>_x000D_
<td>47</td>_x000D_
<td>2011/03/21</td>_x000D_
<td>$356,250</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Lael Greer</td>_x000D_
<td>Systems Administrator</td>_x000D_
<td>London</td>_x000D_
<td>21</td>_x000D_
<td>2009/02/27</td>_x000D_
<td>$103,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jonas Alexander</td>_x000D_
<td>Developer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>30</td>_x000D_
<td>2010/07/14</td>_x000D_
<td>$86,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Shad Decker</td>_x000D_
<td>Regional Director</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>51</td>_x000D_
<td>2008/11/13</td>_x000D_
<td>$183,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Michael Bruce</td>_x000D_
<td>Javascript Developer</td>_x000D_
<td>Singapore</td>_x000D_
<td>29</td>_x000D_
<td>2011/06/27</td>_x000D_
<td>$183,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Donna Snider</td>_x000D_
<td>Customer Support</td>_x000D_
<td>New York</td>_x000D_
<td>27</td>_x000D_
<td>2011/01/25</td>_x000D_
<td>$112,000</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
<tfoot>_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th>Position</th>_x000D_
<th>Office</th>_x000D_
<th>Age</th>_x000D_
<th>Start date</th>_x000D_
<th>Salary</th>_x000D_
</tr>_x000D_
</tfoot>_x000D_
</table>
_x000D_
As of v1.10.5 DataTables can also use initialization options read from HTML5 data-* attributes. This provides a mechanism for setting options directly in your HTML, rather than using Javascript.
Serj-Tm solution is fine, also this is the generic version as extension method for lists (put it into a static class):
public static List<List<T>> Split<T>(this List<T> items, int sliceSize = 30)
{
List<List<T>> list = new List<List<T>>();
for (int i = 0; i < items.Count; i += sliceSize)
list.Add(items.GetRange(i, Math.Min(sliceSize, items.Count - i)));
return list;
}
add semi-colon the line before:
$total_pages = ceil($total_result / $per_page);
Use toFixed
to convert it to a string with some decimal places shaved off, and then convert it back to a number.
+(0.1 + 0.2).toFixed(12) // 0.3
It looks like IE's toFixed
has some weird behavior, so if you need to support IE something like this might be better:
Math.round((0.1 + 0.2) * 1e12) / 1e12
This worked for me:
var dtFromMillisec = new Date(secs*1000);
var result = dtFromMillisec.getHours() + ":" + dtFromMillisec.getMinutes() + ":" + dtFromMillisec.getSeconds();
Use Math.Round
:
double roundedValue = Math.Round(value, 0)
This totally caught me off guard recently. This is because I've programmed in C since the 1970's and I'm only now learning the fine details of Python. Like this curious behavior of math.floor().
The math library of Python is how you access the C standard math library. And the C standard math library is a collection of floating point numerical functions, like sin(), and cos(), sqrt(). The floor() function in the context of numerical calculations has ALWAYS returned a float. For 50 YEARS now. It's part of the standards for numerical computation. For those of us familiar with the math library of C, we don't understand it to be just "math functions". We understand it to be a collection of floating-point algorithms. It would be better named something like NFPAL - Numerical Floating Point Algorithms Libary. :)
Those of us that understand the history instantly see the python math module as just a wrapper for the long-established C floating-point library. So we expect without a second thought, that math.floor() is the same function as the C standard library floor() which takes a float argument and returns a float value.
The use of floor() as a numerical math concept goes back to 1798 per the Wikipedia page on the subject: https://en.wikipedia.org/wiki/Floor_and_ceiling_functions#Notation
It never has been a computer science covert floating-point to integer storage format function even though logically it's a similar concept.
The floor() function in this context has always been a floating-point numerical calculation as all(most) the functions in the math library. Floating-point goes beyond what integers can do. They include the special values of +inf, -inf, and Nan (not a number) which are all well defined as to how they propagate through floating-point numerical calculations. Floor() has always CORRECTLY preserved values like Nan and +inf and -inf in numerical calculations. If Floor returns an int, it totally breaks the entire concept of what the numerical floor() function was meant to do. math.floor(float("nan")) must return "nan" if it is to be a true floating-point numerical floor() function.
When I recently saw a Python education video telling us to use:
i = math.floor(12.34/3)
to get an integer I laughed to myself at how clueless the instructor was. But before writing a snarkish comment, I did some testing and to my shock, I found the numerical algorithms library in Python was returning an int. And even stranger, what I thought was the obvious answer to getting an int from a divide, was to use:
i = 12.34 // 3
Why not use the built-in integer divide to get the integer you are looking for! From my C background, it was the obvious right answer. But low and behold, integer divide in Python returns a FLOAT in this case! Wow! What a strange upside-down world Python can be.
A better answer in Python is that if you really NEED an int type, you should just be explicit and ask for int in python:
i = int(12.34/3)
Keeping in mind however that floor() rounds towards negative infinity and int() rounds towards zero so they give different answers for negative numbers. So if negative values are possible, you must use the function that gives the results you need for your application.
Python however is a different beast for good reasons. It's trying to address a different problem set than C. The static typing of Python is great for fast prototyping and development, but it can create some very complex and hard to find bugs when code that was tested with one type of objects, like floats, fails in subtle and hard to find ways when passed an int argument. And because of this, a lot of interesting choices were made for Python that put the need to minimize surprise errors above other historic norms.
Changing the divide to always return a float (or some form of non int) was a move in the right direction for this. And in this same light, it's logical to make // be a floor(a/b) function, and not an "int divide".
Making float divide by zero a fatal error instead of returning float("inf") is likewise wise because, in MOST python code, a divide by zero is not a numerical calculation but a programming bug where the math is wrong or there is an off by one error. It's more important for average Python code to catch that bug when it happens, instead of propagating a hidden error in the form of an "inf" which causes a blow-up miles away from the actual bug.
And as long as the rest of the language is doing a good job of casting ints to floats when needed, such as in divide, or math.sqrt(), it's logical to have math.floor() return an int, because if it is needed as a float later, it will be converted correctly back to a float. And if the programmer needed an int, well then the function gave them what they needed. math.floor(a/b) and a//b should act the same way, but the fact that they don't I guess is just a matter of history not yet adjusted for consistency. And maybe too hard to "fix" due to backward compatibility issues. And maybe not that important???
In Python, if you want to write hard-core numerical algorithms, the correct answer is to use NumPy and SciPy, not the built-in Python math module.
import numpy as np
nan = np.float64(0.0) / 0.0 # gives a warning and returns float64 nan
nan = np.floor(nan) # returns float64 nan
Python is different, for good reasons, and it takes a bit of time to understand it. And we can see in this case, the OP, who didn't understand the history of the numerical floor() function, needed and expected it to return an int from their thinking about mathematical integers and reals. Now Python is doing what our mathematical (vs computer science) training implies. Which makes it more likely to do what a beginner expects it to do while still covering all the more complex needs of advanced numerical algorithms with NumPy and SciPy. I'm constantly impressed with how Python has evolved, even if at times I'm totally caught off guard.
The Random
class of Java located in the java.util
package will serve your purpose better. It has some nextInt()
methods that return an integer. The one taking an int argument will generate a number between 0 and that int, the latter not inclusive.
It looks like this function I found at weeknumber.net is pretty accurate and easy to use.
// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: http://weeknumber.net/how-to/javascript
// Returns the ISO week of the date.
Date.prototype.getWeek = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
If you're lucky like me and need to find the week number of the month a little adjust will do it:
// Returns the week in the month of the date.
Date.prototype.getWeekOfMonth = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), date.getMonth(), 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
Use Math.ceil()
and cast the result to int:
Example:
(int) Math.ceil((double)divident / divisor);
You are doing 157/32
which is dividing two integers with each other, which always result in a rounded down integer. Therefore the (int) Math.ceil(...)
isn't doing anything. There are three possible solutions to achieve what you want. I recommend using either option 1 or option 2. Please do NOT use option 0.
Convert a
and b
to a double, and you can use the division and Math.ceil
as you wanted it to work. However I strongly discourage the use of this approach, because double division can be imprecise. To read more about imprecision of doubles see this question.
int n = (int) Math.ceil((double) a / b));
int n = a / b + ((a % b == 0) ? 0 : 1);
You do a / b
with always floor if a
and b
are both integers. Then you have an inline if-statement witch checks whether or not you should ceil instead of floor. So +1 or +0, if there is a remainder with the division you need +1. a % b == 0
checks for the remainder.
This option is very short, but maybe for some less intuitive. I think this less intuitive approach would be faster than the double division and comparison approach:
Please note that this doesn't work for b < 0
.
int n = (a + b - 1) / b;
To reduce the chance of overflow you could use the following. However please note that it doesn't work for a = 0
and b < 1
.
int n = (a - 1) / b + 1;
Since dividing two integer in Java (and most other programming languages) will always floor the result. So:
int a, b;
int result = a/b (is the same as floor(a/b) )
But we don't want floor(a/b)
, but ceil(a/b)
, and using the definitions and plots from Wikipedia:
With these plots of the floor and ceil function you can see the relationship.
You can see that floor(x) <= ceil(x)
. We need floor(x + s) = ceil(x)
. So we need to find s
. If we take 1/2 <= s < 1
it will be just right (try some numbers and you will see it does, I find it hard myself to prove this). And 1/2 <= (b-1) / b < 1
, so
ceil(a/b) = floor(a/b + s)
= floor(a/b + (b-1)/b)
= floor( (a+b-1)/b) )
This is not a real proof, but I hope your are satisfied with it. If someone can explain it better I would appreciate it too. Maybe ask it on MathOverflow.
int RoundedUp = (int) Math.ceil(RandomReal);
This seemed to do the perfect job. Worked everytime.
function formatSeconds(s: number) {
let minutes = ~~(s / 60);
let seconds = ~~(s % 60);
return minutes + ':' + seconds;
}
It's caused by n % x
, when x
is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.
General notes:
q
to be global.You need to set the value of $title
before echoing it.
Also, you should really sanitize any data before using it in queries as this is a security risk
df['Column_Name']=df['Column_Name'].astype(int)
Two things. First, you must base64 decode the mykey.pem
file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey
ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec
, which is based on the SubjectPublicKeyInfo
ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
// ...
String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);
You could use the div
function in cstdlib to get the quotient & remainder in a single call and then handle the ceiling separately, like in the below
#include <cstdlib>
#include <iostream>
int div_ceil(int numerator, int denominator)
{
std::div_t res = std::div(numerator, denominator);
return res.rem ? (res.quot + 1) : res.quot;
}
int main(int, const char**)
{
std::cout << "10 / 5 = " << div_ceil(10, 5) << std::endl;
std::cout << "11 / 5 = " << div_ceil(11, 5) << std::endl;
return 0;
}
Here's my take
I'm not so sure about it's performance, but I find it much more readable than other options I saw around here...
var replicate = function(len, char) {
return Array(len+1).join(char || ' ');
};
var padr = function(text, len, char) {
if (text.length >= len) return text;
return text + replicate(len-text.length, char);
};
The other answers here work for something like Math, which is a static object. But they don't work for an instance of an object, such as a date. I found the following to work:
function getMethods(o) {
return Object.getOwnPropertyNames(Object.getPrototypeOf(o))
.filter(m => 'function' === typeof o[m])
}
//example: getMethods(new Date()): [ 'getFullYear', 'setMonth', ... ]
https://jsfiddle.net/3xrsead0/
This won't work for something like the original question (Math), so pick your solution based on your needs. I'm posting this here because Google sent me to this question but I was wanting to know how to do this for instances of objects.
You can get around that limit by using subst if you need to.
You can cast to an int provided you are sure it's in the range for an int (Int32.MinValue to Int32.MaxValue).
This is not related to the original question, but i had the same error-message and this thread is the first hit in Google and it took me a while to figure out what the Problem was, so it May be of use for others:
i'm NOT using mysqli, still using mysql_connect i had some simple querys, but ONE query caused all other querys to fail within the same Connection.
I use mysql 5.7 and php 5.6 i had a table with the data-Type "JSON". obviously, my php-version did not recognize the return value from mysql (php just did not know what to do with the JSON-Format because the built-in mysql-module was too old (at least i think))
for now i changed the JSON-Field-Type to Text (as for now i don't need the native mysql JSON-functionality) and everything works fine
// Convert the float to a string
// We might use stringstream, but it looks like it truncates the float to only
//5 decimal points (maybe that's what you want anyway =P)
float MyFloat = 5.11133333311111333;
float NewConvertedFloat = 0.0;
string FirstString = " ";
string SecondString = " ";
stringstream ss (stringstream::in | stringstream::out);
ss << MyFloat;
FirstString = ss.str();
// Take out how ever many decimal places you want
// (this is a string it includes the point)
SecondString = FirstString.substr(0,5);
//whatever precision decimal place you want
// Convert it back to a float
stringstream(SecondString) >> NewConvertedFloat;
cout << NewConvertedFloat;
system("pause");
It might be an inefficient dirty way of conversion but heck, it works lol. And it's good, because it applies to the actual float. Not just affecting the output visually.
In most cases you should allow the thread pool to handle this. If you post some code or give more details it might be easier to see if there is some reason the default behavior of the thread pool would not be best.
You can find more information on how this should work here: http://en.wikipedia.org/wiki/Thread_pool_pattern
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
Your vncserver have a configuration file somewher that set the display number. To do it automaticaly, one solution is to parse this file, extract the number and set it correctly. A simpler (better) is to have this display number set in a config script and use it in both your VNC server config and in your init scripts.
It is possible of course, use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
written out, as opposed to -lXYZ
which would auto expand to libXYZ
.
I know this is a rather old question as of now, but I had found the proper solution was that I was not declaring the assembly attribute.
My code is:
using AutoMapper;
...
namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}
This was fixed by adding the following line before my namespace declaration:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]
The full code is:
using AutoMapper;
...
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]
namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}
This the code in c# to find the solution.
public struct CoinCount
{
public int coinValue;
public int noOfCoins;
}
/// <summary>
/// Find and returns the no of coins in each coins in coinSet
/// </summary>
/// <param name="coinSet">sorted coins value in assending order</param>
/// <returns></returns>
public CoinCount[] FindCoinsCountFor1to99Collection(int[] coinSet)
{
// Add extra coin value 100 in the coin set. Since it need to find the collection upto 99.
CoinCount[] result = new CoinCount[coinSet.Length];
List<int> coinValues = new List<int>();
coinValues.AddRange(coinSet);
coinValues.Add(100);
// Selected coin total values
int totalCount = 0;
for (int i = 0; i < coinValues.Count - 1; i++)
{
int count = 0;
if (totalCount <= coinValues[i])
{
// Find the coins count
int remainValue = coinValues[i + 1] - totalCount;
count = (int)Math.Ceiling((remainValue * 1.0) / coinValues[i]);
}
else
{
if (totalCount <= coinValues[i + 1])
count = 1;
else
count = 0;
}
result[i] = new CoinCount() { coinValue = coinValues[i], noOfCoins = count };
totalCount += coinValues[i] * count;
}
return result;
}
There is no mention about nine-patch files here. Yes, you have to create the file, however it's quite easy job and it's really "cross-version and transparency supporting" solution. If the file is placed to the drawable-nodpi
directory, it works px
based, and in the drawable-mdpi
works approximately as dp base (thanks to resample).
Example file for the original question (border-right:1px solid red;) is here:
Just place it to the drawable-nodpi
directory.
I have fixed the same issue with below steps
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === 'the-provided-hash-code') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php php -r "unlink('composer-setup.php');"
Everything is working fine now because the composer.phar
file is available within the current project directory.
Copied from https://stackoverflow.com/questions/21670709/running-composer-returns-could-not-open-input-file-composer-phar/51907013#51907013
thanks
This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression
technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.
Use a CSS rule like so:
body {
behavior:url(script.htc);
}
and within that script.htc file have something like:
<PUBLIC:COMPONENT TAGNAME="xss">
<PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
function main()
{
alert("HTC script executed.");
}
</SCRIPT>
The HTC file executes the main()
function on the event ondocumentready
(referring to the HTC document's readiness.)
Firefox supports a similar XML-script-executing hack, using XBL.
Use a CSS rule like so:
body {
-moz-binding: url(script.xml#mycode);
}
and within your script.xml:
<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="mycode">
<implementation>
<constructor>
alert("XBL script executed.");
</constructor>
</implementation>
</binding>
</bindings>
All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)
In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body
, it will execute immediately on page load.
you can use the return
statement without any parameter to exit a function
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
return
do much much more...
or raise an exception if you want to be informed of the problem
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
raise Exception("cause of the problem")
do much much more...
In the jquery ready function you can do something like below -
var hrefcode = $('a[id*=linkbutton]').attr('href').split(':');
var onclickcode = "javascript: if`(Condition()) {" + hrefcode[1] + ";}";
$('a[id*=linkbutton]').attr('href', onclickcode);
You could use use max
and min
with dict.get
:
maximum = max(mydict, key=mydict.get) # Just use 'min' instead of 'max' for minimum.
print(maximum, mydict[maximum])
# D 87
Something else you can use is isnull
:
isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)
another solution , you can add <br>
tag to your table
|Method name| Behavior |
|--|--|
| OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|
Objective C Code
MyTextField.h
#import <UIKit/UIKit.h>
@interface MyTextField : UITextField
@property (nonatomic) IBInspectable CGFloat padding;
@end
MyTextField.m
#import "MyTextField.h"
IB_DESIGNABLE
@implementation MyTextField
@synthesize padding;
-(CGRect)textRectForBounds:(CGRect)bounds{
return CGRectInset(bounds, padding, padding);
}
-(CGRect)editingRectForBounds:(CGRect)bounds{
return [self textRectForBounds:bounds];
}
@end
My partial context looks like:
public partial class MyContext : DbContext
{
public MyContext (string ConnectionString)
: base(ConnectionString)
{
this.SetCommandTimeOut(300);
}
public void SetCommandTimeOut(int Timeout)
{
var objectContext = (this as IObjectContextAdapter).ObjectContext;
objectContext.CommandTimeout = Timeout;
}
}
I left SetCommandTimeOut
public so only the routines I need to take a long time (more than 5 minutes) I modify instead of a global timeout.
If you're a fan of NumPy
ish syntax, then there's tensor.shape
.
In [3]: ar = torch.rand(3, 3)
In [4]: ar.shape
Out[4]: torch.Size([3, 3])
# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]
# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]
# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]
P.S.: Note that tensor.shape
is an alias to tensor.size()
, though tensor.shape
is an attribute of the tensor in question whereas tensor.size()
is a function.
Here's a nice way (not mine, the original reference is here: http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html
I've used this approach and it works fine. Basically it's a simple bean that holds a (static) reference to the application context. By referencing it in the spring config it's initialized.
Take a look at the original ref, it's very clear.
Chances that you already got the source code with the JDK, it is matter of finding where it is. In case, JDK folder doesn't contain the source code:
sudo apt-get install openjdk-7-source
OSX Folks, search in homebrew formulas.
In ubuntu, the command above would put your souce file under: /usr/lib/jvm/openjdk-7/
Good news is that Eclipse will take you there already (How to bind Eclipse to the Java source code):
Follow the orange buttons
function sortMultiFields(prop){
return function(a,b){
for(i=0;i<prop.length;i++)
{
var reg = /^\d+$/;
var x=1;
var field1=prop[i];
if(prop[i].indexOf("-")==0)
{
field1=prop[i].substr(1,prop[i].length);
x=-x;
}
if(reg.test(a[field1]))
{
a[field1]=parseFloat(a[field1]);
b[field1]=parseFloat(b[field1]);
}
if( a[field1] > b[field1])
return x;
else if(a[field1] < b[field1])
return -x;
}
}
}
How to use (put -(minus) sign before field if you want to sort in descending order particular field)
homes.sort(sortMultiFields(["city","-price"]));
Using above function you can sort any json array with multiple fields. No need to change function body at all
If the input value gets populated by a script that has some latency involved (e.g. AJAX call) then you need to wait until the input has been populated. E.g.
var w = new WebDriverWait(WebBrowser, TimeSpan.FromSeconds(10));
w.Until((d) => {
// Wait until the input has a value...
var elements = d.FindElements(By.Name(name));
var ele = elements.SingleOrDefault();
if (ele != null)
{
// Found a single element
if (ele.GetAttribute("value") != "")
{
// We have a value now
return true;
}
}
return false;
});
var e = WebBrowser.Current.FindElement(By.Name(name));
if (e.GetAttribute("value") != value)
{
Assert.Fail("Result contains a field named '{0}', but its value is '{1}', not '{2}' as expected", name, e.GetAttribute("value"), value);
}
When you have unmanaged resources and you need to make sure they will be cleaned up when your object goes away. Good example would be COM objects or File Handlers.
One more option, not exactly what you asked, but can be useful:
Go to Settings
-> Editor
-> File and code templates
-> Includes
tab (on the right). There is a template header for the new files, you can use the username here:
/**
* @author myname
*/
For system username use:
/**
* @author ${USER}
*/
Factory Design Pattern
The factory design pattern is characterized by
You can observe few things when you question yourself as below
These are handled by Dependency injection.
Dependency injection
You can have different ways in which you can inject dependency. For simplicity lets go with Interface Injection
In DI ,container creates the needed instances, and "injects" them into the object.
Thus eliminates the static instantiation.
Example:
public class MyClass{
MyInterface find= null;
//Constructor- During the object instantiation
public MyClass(MyInterface myInterface ) {
find = myInterface ;
}
public void myMethod(){
find.doSomething();
}
}
SELECT *
FROM (SELECT * FROM can
UNION
SELECT * FROM employee) as e
WHERE e.id = 1;
You can also use references on foreach
values:
foreach($array as $elementKey => &$element) {
// $element is the same than &$array[$elementKey]
if (isset($element['id']) and $element['id'] == 'searched_value') {
unset($element);
}
}
If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide()
, with additional arguments, as follows:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this).hide('slide',{direction:'right'},1000);
});
});
Without using jQuery UI, you could achieve your aim just using animate()
:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this)
.animate(
{
'margin-left':'1000px'
// to move it towards the right and, probably, off-screen.
},1000,
function(){
$(this).slideUp('fast');
// once it's finished moving to the right, just
// removes the the element from the display, you could use
// `remove()` instead, or whatever.
}
);
});
});
If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
I do a lot of Novell Identity Manager stuff, and XPATH in that context looks a little different.
Assume the value you are looking for is in a string variable, called TARGET, then the XPATH would be:
count(attr/value[.='$TARGET']/preceding-sibling::*)+1
Additionally it was pointed out that to save a few characters of space, the following would work as well:
count(attr/value[.='$TARGET']/preceding::*) + 1
I also posted a prettier version of this at Novell's Cool Solutions: Using XPATH to get the position node
In Java, you can use TagSoup.
As far as it is not cross browser solution, you might be take advantage of using calc(expression)
to achive that.
html, body {
height: 100%;
}
header {
height: 50px;
background-color: tomato
}
#content {
height: -moz-calc(100% - 100px); /* Firefox */
height: -webkit-calc(100% - 100px); /* Chrome, Safari */
height: calc(100% - 100px); /* IE9+ and future browsers */
background-color: yellow
}
footer {
height: 50px;
background-color: grey;
}
If you want to know more about calc(expression)
you'd better to visit this site.
Another option is Sheet1.Rows(x & ":" & Sheet1.Rows.Count).ClearContents
(or .Clear
). The reason you might want to use this method instead of .Delete
is because any cells with dependencies in the deleted range (e.g. formulas that refer to those cells, even if empty) will end up showing #REF
. This method will preserve formula references to the cleared cells.
If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.
On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:
You can do it without telling the full Acrobat path, like this:
Process myProcess = new Process();
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();
If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:
myProcess.StartInfo.FileName = "Acrobat.exe";
You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.
Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows
According to the official documentation on sitemaps.org it needs to be a full URL:
You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:
Sitemap: http://www.example.com/sitemap.xml
By adding filter action my problem resolved
// Register for broadcasts when a device is discovered
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, intentFilter);
If you don't want to have to add the stop propagation to all links this works as well. A bit more scalable.
$scope.hideOverlay( $event ){
// only hide the overlay if we click on the actual div
if( $event.target.className.indexOf('overlay') )
// hide overlay logic
}
The size_t type is the type returned by the sizeof operator. It is an unsigned integer capable of expressing the size in bytes of any memory range supported on the host machine. It is (typically) related to ptrdiff_t in that ptrdiff_t is a signed integer value such that sizeof(ptrdiff_t) and sizeof(size_t) are equal.
When writing C code you should always use size_t whenever dealing with memory ranges.
The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic. For example, on many older PC type computers the value sizeof(size_t) would be 4 (bytes) but sizeof(int) would be 2 (byte). 16 bit arithmetic was faster than 32 bit arithmetic, though the CPU could handle a (logical) memory space of up to 4 GiB.
Use the int type only when you care about efficiency as its actual precision depends strongly on both compiler options and machine architecture. In particular the C standard specifies the following invariants: sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) placing no other limitations on the actual representation of the precision available to the programmer for each of these primitive types.
Note: This is NOT the same as in Java (which actually specifies the bit precision for each of the types 'char', 'byte', 'short', 'int' and 'long').
You should use data.response
in your JS instead of json.response
.
You dont have to
RUN mkdir -p /usr/src/app
This will be created automatically when you specifiy your WORKDIR
FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ “npm”, “start” ]
I see two parts to this:
Note that you can perfectly well use Spring in a web application without using Spring MVC. I would say most Java web applications do this, while using other web frameworks like Wicket, Struts, Seam, ...
It is rule of thumb that the first layer in your network should be the same shape as your data. For example our data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to 'flatten' that 28,28 into a 784x1. Instead of wriitng all the code to handle that ourselves, we add the Flatten() layer at the begining, and when the arrays are loaded into the model later, they'll automatically be flattened for us.
Relocation R_X86_64_PC32 against undefined symbol , usually happens when LDFLAGS are set with hardening and CFLAGS not .
Maybe just user error:
If you are using -specs=/usr/lib/rpm/redhat/redhat-hardened-ld at link time,
you also need to use -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 at compile time, and as you are compiling and linking at the same time, you need either both, or drop the -specs=/usr/lib/rpm/redhat/redhat-hardened-ld .
Common fixes :
https://bugzilla.redhat.com/show_bug.cgi?id=1304277#c3
https://github.com/rpmfusion/lxdream/blob/master/lxdream-0.9.1-implicit.patch
You can use Microsoft.Jet.OLEDB.4.0
Running docker with interactive mode might solve the issue.
Here is the example for running image with and without interactive mode
chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker run -d -t -i test_again1.0 b6b9a942a79b1243bada59db19c7999cfff52d0a8744542fa843c95354966a18
chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker run -d -t -i test_again1.0 bash c3d6a9529fd70c5b2dc2d7e90fe662d19c6dad8549e9c812fb2b7ce2105d7ff5
chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c3d6a9529fd7 test_again1.0 "bash" 2 seconds ago Up 1 second awesome_haibt
When we use CommandObj.Parameter.Add()
it takes 2 parameters, the first is procedure parameter and the second is its data type, while .AddWithValue()
takes 2 parameters, the first is procedure parameter and the second is the data variable
CommandObj.Parameter.Add("@ID",SqlDbType.Int).Value=textBox1.Text;
for .AddWithValue
CommandObj.Parameter.AddWitheValue("@ID",textBox1.Text);
where ID
is the parameter of stored procedure which data type is Int
If you use Spring framework in your project, then you can use StringUtils
import org.springframework.util.StringUtils;
StringUtils.getFilenameExtension("YourFileName")
You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging
Public Sub test(mdate As String)
Dim toDay As String
mdate = Round(CDbl(CDate(mdate)), 0)
toDay = Round(CDbl(Now()), 0)
Dim Aging as String
Aging = toDay - mdate
MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub
NB: Used CDate
for convert Date String to Valid Date
I am using this in Office 2007 :)
If you want the password prompt to go away then use key based authentication (described here).
To run commands remotely over ssh you have to give them as an argument to ssh, like the following:
root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'
HTML
<Select id="SDistrict" class="form-control">
<option value="1" data-color="yellow" > Mango </option>
</select>
JS when initialized
$('#SDistrict').selectize({
create: false,
sortField: 'text',
onInitialize: function() {
var s = this;
this.revertSettings.$children.each(function() {
$.extend(s.options[this.value], $(this).data());
});
},
onChange: function(value) {
var option = this.options[value];
alert(option.text + ' color is ' + option.color);
}
});
You can access data attribute of option tag with option.[data-attribute]
JS Fiddle : https://jsfiddle.net/shashank_p/9cqoaeyt/3/
Use assets like a filesystem to dump any kind of files. And use res to store what it is made for, layouts, images, values.
For me, eclipse was looking in the wrong place for the SDK Manager. To fix this I did
NOTE: The SDK manager tells you what dir it is using near the top of the UI.
I had installed a new version of eclipse that has the ADT bundled up from the Android developer site, but when I opened eclipse it was looking at the old SDK.exe location.
hth
https://socket.io/docs/client-api/#socket-send-args-ack
socket.send
// Sends a message event
socket.emit(eventName[, ...args][, ack])
// you can custom eventName
It is not possible to resize an array. However, it is possible change the size of an array through copying the original array to the newly sized one and keep the current elements. The array can also be reduced in size by removing an element and resizing.
import java.util.Arrays
public class ResizingArray {
public static void main(String[] args) {
String[] stringArray = new String[2] //A string array with 2 strings
stringArray[0] = "string1";
stringArray[1] = "string2";
// increase size and add string to array by copying to a temporary array
String[] tempStringArray = Arrays.copyOf(stringArray, stringArray.length + 1);
// Add in the new string
tempStringArray[2] = "string3";
// Copy temp array to original array
stringArray = tempStringArray;
// decrease size by removing certain string from array (string1 for example)
for(int i = 0; i < stringArray.length; i++) {
if(stringArray[i] == string1) {
stringArray[i] = stringArray[stringArray.length - 1];
// This replaces the string to be removed with the last string in the array
// When the array is resized by -1, The last string is removed
// Which is why we copied the last string to the position of the string we wanted to remove
String[] tempStringArray2 = Arrays.copyOf(arrayString, arrayString.length - 1);
// Set the original array to the new array
stringArray = tempStringArray2;
}
}
}
}
use this code
var sid = $(this);
sid.attr('checked','checked');
Bass can do just this. Play from Byte[] in memory or a through file delegates where you return the data, so with that you can play as soon as you have enough data to start the playback..
you can use layout_constraintCircle for center view inside ConstraintLayout.
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mparent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/btn_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_home_black_24dp"
app:layout_constraintCircle="@id/mparent"
app:layout_constraintCircleRadius="0dp"
/>
</android.support.constraint.ConstraintLayout>
with constraintCircle to parent and zero radius you can make your view be center of parent.
Create a listview item
ListViewItem item1 = new ListViewItem("sdasdasdasd", 0)
item1.SubItems.Add("asdasdasd")
In order to overcome
Ambiguous output in step `CR-LF..data'
simply solution might be to add -f
flag to force conversion.
According to some comments on Super User it still works :) It just should be copied back to the plugins folder (if it's in the disabled folder) or downloaded from Plugins Central. I have downloaded it a few minutes ago and succeeded in using it.
Of course, be warned: this plugin COULD be unstable in some situations - that's why it was disabled.
(EDIT: As pointed out by the OP, the using a java.net.Authenticator
is required too. I'm updating my answer accordingly for the sake of correctness.)
(EDIT#2: As pointed out in another answer, in JDK 8 it's required to remove basic
auth scheme from jdk.http.auth.tunneling.disabledSchemes
property)
For authentication, use java.net.Authenticator
to set proxy's configuration and set the system properties http.proxyUser
and http.proxyPassword
.
final String authUser = "user";
final String authPassword = "password";
Authenticator.setDefault(
new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
}
);
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
I like to use the following approach for headers on a ComboBox where the CboBx is not loaded from a worksheet (data from sql for example). The reason I specify not from a worksheet is that I think the only way to get RowSource to work is if you load from a worksheet.
This works for me:
In your VBA for the action yourListBoxName_Click, enter the following code:
yourComboBoxName.Activate`
yourComboBoxName.DropDown`
When you click on the listbox, the combobox will drop down and function normally while the headings (in the listbox) remain above the list.
Typically for dynamic lists of items, you use a std::vector
.
Generally I use memset or a loop for raw memory dynamic allocation, depending on how variable I anticipate that area of code to be in the future.
I know it is an old question, but I had a similar trouble recently. On VMware Workstation 12.+ go to Edit -> Virtual Network Editor...
Select a network used by the problematic VM and make sure that "Connect a host virtual adapter to this network"
checkbox is set for this network. In my case, it was not. After it was set, the host was able to ping the guest and guests were able to talk to each other.
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.this worked for me fine!
shell_command = "ls -l"
subprocess.call(shell_command.split())
Do mean to check if $a is a non-empty string? So that it contains just any text? Then the following will work.
If $a contains a string, you can use the following:
if (!empty($a)) { // Means: if not empty
...
}
If you also need to confirm that $a is actually a string, use:
if (is_string($a) && !empty($a)) { // Means: if $a is a string and not empty
...
}
When using GetAsync with the HttpClient you can add the authorization headers like so:
httpClient.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "Your Oauth token");
This does add the authorization header for the lifetime of the HttpClient so is useful if you are hitting one site where the authorization header doesn't change.
Here is an detailed SO answer
Should be pretty straightforward, its just the reverse of your previous method;
public static int GetEnumFromDescription(string description, Type enumType)
{
foreach (var field in enumType.GetFields())
{
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
if(attribute == null)
continue;
if(attribute.Description == description)
{
return (int) field.GetValue(null);
}
}
return 0;
}
Usage:
Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));
Constraints dictate what values are valid for data in the database. For example, you can enforce the a value is not null (a NOT NULL
constraint), or that it exists as a unique constraint in another table (a FOREIGN KEY
constraint), or that it's unique within this table (a UNIQUE
constraint or perhaps PRIMARY KEY
constraint depending on your requirements). More general constraints can be implemented using CHECK
constraints.
The MSDN documentation for SQL Server 2008 constraints is probably your best starting place.
If you want to use the reset_index
method and also preserve your existing index you should use:
df.reset_index().set_index('index', drop=False)
or to change it in place:
df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)
For example:
print(df)
gi ptt_loc
0 384444683 593
4 384444684 594
9 384444686 596
print(df.reset_index())
index gi ptt_loc
0 0 384444683 593
1 4 384444684 594
2 9 384444686 596
print(df.reset_index().set_index('index', drop=False))
index gi ptt_loc
index
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
And if you want to get rid of the index label you can do:
df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
index gi ptt_loc
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
This is a late answer, but by looking at the source code, I noticed that when the video is fullscreen, the "mejs-container-fullscreen" class is added to the "mejs-container" element. It is thus possible to change the styling based on this class.
.mejs-container.mejs-container-fullscreen {
// This rule applies only to the container when in fullscreen
padding-top: 57%;
}
Also, if you wish to make your MediaElement video fluid using CSS, below is a great trick by Chris Coyier: http://css-tricks.com/rundown-of-handling-flexible-media/
Just add this to your CSS:
.mejs-container {
width: 100% !important;
height: auto !important;
padding-top: 57%;
}
.mejs-overlay, .mejs-poster {
width: 100% !important;
height: 100% !important;
}
.mejs-mediaelement video {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
width: 100% !important;
height: 100% !important;
}
I hope it helps.
The title
attribute works on most HTML tags and is widely supported by modern browsers.
Using nltk.
from nltk.tokenize import sent_tokenize, word_tokenize
sentences = sent_tokenize("This is a string.")
words_in_each_sentence = word_tokenize(sentences)
You may use TweetTokenizer for parsing casual text with emoticons and such.
Assign after the EXEC
token:
DECLARE @returnValue INT
EXEC @returnValue = SP_One
This SO question is missing the following approach :
-- List down all columns of table 'Logging'
select * from sys.all_columns where object_id = OBJECT_ID('Logging')
I have been busy with a similar problem, and I'm quite puzzled by the results. I was calculating x?³/² for Newtonian gravitation in an n-bodies situation (acceleration undergone from another body of mass M situated at a distance vector d) : a = M G d*(d²)?³/²
(where d² is the dot (scalar) product of d by itself) , and I thought calculating M*G*pow(d2, -1.5)
would be simpler than M*G/d2/sqrt(d2)
The trick is that it is true for small systems, but as systems grow in size, M*G/d2/sqrt(d2)
becomes more efficient and I don't understand why the size of the system impacts this result, because repeating the operation on different data does not. It is as if there were possible optimizations as the system grow, but which are not possible with pow
Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that
let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"
It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?
Since none of the suggestions above helped me with charts.js 2.1.4, I solved it by adding the value 0 to my data set array (but no extra label):
statsData.push(0);
[...]
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
datasets: [{
data: statsData,
[...]
There's a book in Martin Fowler's Signature Series called Refactoring Databases. That provides a list of techniques for refactoring databases. I can't say I've heard a list of database patterns so much.
I would also highly recommend David C. Hay's Data Model Patterns and the follow up A Metadata Map which builds on the first and is far more ambitious and intriguing. The Preface alone is enlightening.
Also a great place to look for some pre-canned database models is Len Silverston's Data Model Resource Book Series Volume 1 contains universally applicable data models (employees, accounts, shipping, purchases, etc), Volume 2 contains industry specific data models (accounting, healthcare, etc), Volume 3 provides data model patterns.
Finally, while this book is ostensibly about UML and Object Modelling, Peter Coad's Modeling in Color With UML provides an "archetype" driven process of entity modeling starting from the premise that there are 4 core archetypes of any object/data model
If you are using MAC Catalina you need to update the .zshrc file instead of .bash_profile or .profile
This line:
setTimeout(startTimer(), startInterval);
You're invoking startTimer()
. Instead, you need to pass it in as a function to be invoked, like so:
setTimeout(startTimer, startInterval);
Best of all,
Go and choose your language, and then it'll give you the file.
As you correctly point out, one can ReDim Preserve
only the last dimension of an array (ReDim Statement on MSDN):
If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array
Hence, the first issue to decide is whether 2-dimensional array is the best data structure for the job. Maybe, 1-dimensional array is a better fit as you need to do ReDim Preserve
?
Another way is to use jagged array as per Pieter Geerkens's suggestion. There is no direct support for jagged arrays in VB6. One way to code "array of arrays" in VB6 is to declare an array of Variant
and make each element an array of desired type (String
in your case). Demo code is below.
Yet another option is to implement Preserve
part on your own. For that you'll need to create a copy of data to be preserved and then fill redimensioned array with it.
Option Explicit
Public Sub TestMatrixResize()
Const MAX_D1 As Long = 2
Const MAX_D2 As Long = 3
Dim arr() As Variant
InitMatrix arr, MAX_D1, MAX_D2
PrintMatrix "Original array:", arr
ResizeMatrix arr, MAX_D1 + 1, MAX_D2 + 1
PrintMatrix "Resized array:", arr
End Sub
Private Sub InitMatrix(a() As Variant, n As Long, m As Long)
Dim i As Long, j As Long
Dim StringArray() As String
ReDim a(n)
For i = 0 To n
ReDim StringArray(m)
For j = 0 To m
StringArray(j) = i * (m + 1) + j
Next j
a(i) = StringArray
Next i
End Sub
Private Sub PrintMatrix(heading As String, a() As Variant)
Dim i As Long, j As Long
Dim s As String
Debug.Print heading
For i = 0 To UBound(a)
s = ""
For j = 0 To UBound(a(i))
s = s & a(i)(j) & "; "
Next j
Debug.Print s
Next i
End Sub
Private Sub ResizeMatrix(a() As Variant, n As Long, m As Long)
Dim i As Long
Dim StringArray() As String
ReDim Preserve a(n)
For i = 0 To n - 1
StringArray = a(i)
ReDim Preserve StringArray(m)
a(i) = StringArray
Next i
ReDim StringArray(m)
a(n) = StringArray
End Sub
Here's working example with anonymous output record, if you have any questions place a comment below:
public partial class Form1 : Form
{
DataTable table;
public Form1()
{
InitializeComponent();
#region TestData
table = new DataTable();
table.Clear();
for (int i = 1; i < 12; ++i)
table.Columns.Add("Col" + i);
for (int rowIndex = 0; rowIndex < 5; ++rowIndex)
{
DataRow row = table.NewRow();
for (int i = 0; i < table.Columns.Count; ++i)
row[i] = String.Format("row:{0},col:{1}", rowIndex, i);
table.Rows.Add(row);
}
#endregion
bind();
}
public void bind()
{
var filtered = from t in table.AsEnumerable()
select new
{
col1 = t.Field<string>(0),//column of index 0 = "Col1"
col2 = t.Field<string>(1),//column of index 1 = "Col2"
col3 = t.Field<string>(5),//column of index 5 = "Col6"
col4 = t.Field<string>(6),//column of index 6 = "Col7"
col5 = t.Field<string>(4),//column of index 4 = "Col3"
};
filteredData.AutoGenerateColumns = true;
filteredData.DataSource = filtered.ToList();
}
}
Use git rebase
. Specifically:
git stash
to store the changes you want to add.git rebase -i HEAD~10
(or however many commits back you want to see).a0865...
) for edit by changing the word pick
at the start of the line into edit
. Don't delete the other lines as that would delete the commits.[^vimnote]git stash pop
git add <file>
.git commit --amend --no-edit
.git rebase --continue
which will rewrite the rest of your commits against the new one.[^vimnote]: If you are using vim
then you will have to hit the Insert key to edit, then Esc and type in :wq
to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano"
.
Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.
In the case of local variables you can not use any kind of accessor (public, protected or private).
You should also know what the static keyword means. In method checkYourself
, you use the Integer array locations
.
The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.
public class Test { //Capitalized name for classes are used in Java
private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later.
public Test(int[] locations) {
this.locations = locations;//To access to class member, when method argument has the same name use `this` key word.
}
public boolean checkYourSelf(int value) { //This method is accessed only from a object.
for(int location : locations) {
if(location == value) {
return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
}
}
return false; //Method should be simple and perform one task. So you can get more flexibility.
}
public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it.
public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.
String result;
if(test.checkYourSelf(2)) {//We moved outside the string
result = "Hurray";
} else {
result = "Try again"
}
System.out.println(result); //We have only one place where write is done. Easy to change in future.
}
}
jQuery is just wrapping the standard resize
DOM event, eg.
window.onresize = function(event) {
...
};
jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ, but I'd encourage you to test in Firefox, Safari, and IE.
First, you should use any WebSocket or polling mechanics to notify the frontend part about changes that happened. I use Flask-SocketIO
wrapper, and very happy with async messaging for my tiny apps.
Nest, you can do all logic which you need in a separate thread(s), and notify the frontend via SocketIO
object (Flask holds continuous open connection with every frontend client).
As an example, I just implemented page reload on backend file modifications:
<!doctype html>
<script>
sio = io()
sio.on('reload',(info)=>{
console.log(['sio','reload',info])
document.location.reload()
})
</script>
class App(Web, Module):
def __init__(self, V):
## flask module instance
self.flask = flask
## wrapped application instance
self.app = flask.Flask(self.value)
self.app.config['SECRET_KEY'] = config.SECRET_KEY
## `flask-socketio`
self.sio = SocketIO(self.app)
self.watchfiles()
## inotify reload files after change via `sio(reload)``
def watchfiles(self):
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Handler(FileSystemEventHandler):
def __init__(self,sio):
super().__init__()
self.sio = sio
def on_modified(self, event):
print([self.on_modified,self,event])
self.sio.emit('reload',[event.src_path,event.event_type,event.is_directory])
self.observer = Observer()
self.observer.schedule(Handler(self.sio),path='static',recursive=True)
self.observer.schedule(Handler(self.sio),path='templates',recursive=True)
self.observer.start()
I came here through Google looking for an answer to how to setup cloud init to not disable PasswordAuthentication on AWS. Both the answers don't address the issue. Without it, if you create an AMI then on instance initialization cloud init will again disable this option.
The correct method to do this, is instead of manually changing sshd_config you need to correct the setting for cloud init (Open source tool used to configure an instance during provisioning. Read more at: https://cloudinit.readthedocs.org/en/latest/). The configuration file for cloud init is found at: /etc/cloud/cloud.cfg
This file is used for setting up a lot of the configuration used by cloud init. Read through this file for examples of items you can configure on cloud-init. This includes items like default username on a newly created instance)
To enable or disable password login over SSH you need to change the value for the parameter ssh_pwauth. After changing the parameter ssh_pwauth from 0 to 1 in the file /etc/cloud/cloud.cfg bake an AMI. If you launch from this newly baked AMI it will have password authentication enabled after provisioning.
You can confirm this by checking the value of the PasswordAuthentication in the ssh config as mentioned in the other answers.
The following code will work:
ComboBox1.SelectedIndex.Equals(String.Empty);
#navigation .navigationLevel2 li
{
color: #f00;
}
In plain English:
->It is located in $MAVEN_HOME/conf/settings.xml... where $MAVEN_HOME is your environmental variable of Maven that you have downloaded. Else you can do like this also.. ->Path to Maven can also be found from /etc/bashrc file in mac. Get Path to Maven from that file and in that Maven directory you can find conf/ directory inside that directory you can find settings.xml of maven
First you should change the password using terminal. (username is postgres)
postgres=# \password postgres
Then you will be prompted to enter the password and confirm it.
Now you will be able to connect using pgadmin with the new password.
promiseA(pram).then(
result => {
//make sure promiseA function allready success and response
//do something here
}).catch(err => console.log(err)) => {
// handle error with try catch
}
Try something like this (should work for Apache and IIS):
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
$location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $location);
exit;
}
If you work in magento and you have this type of associative array
$test_array = array (
'0' => array (
'category_id' => '582',
'name' => 'Surat',
'parent_id' => '565',
'child_id' => '567',
'active' => '1',
'level' => '6',
'position' => '17'
),
'1' => array (
'category_id' => '567',
'name' => 'test',
'parent_id' => '0',
'child_id' => '576',
'active' => '0',
'level' => '0',
'position' => '18'
),
);
then this is best to convert associative array to xml format.Use this code in controller file.
$this->loadLayout(false);
//header ("content-type: text/xml");
$this->getResponse()->setHeader('Content-Type','text/xml');
$this->renderLayout();
$clArr2xml = new arr2xml($test_array, 'utf-8', 'listdata');
$output = $clArr2xml->get_xml();
print $output;
class arr2xml
{
var $array = array();
var $xml = '';
var $root_name = '';
var $charset = '';
public function __construct($array, $charset = 'utf-8', $root_name = 'root')
{
header ("content-type: text/xml");
$this->array = $array;
$this->root_name = $root_name;
$this->charset = $charset;
if (is_array($array) && count($array) > 0) {
$this->struct_xml($array);
} else {
$this->xml .= "no data";
}
}
public function struct_xml($array)
{
foreach ($array as $k => $v) {
if (is_array($v)) {
$tag = ereg_replace('^[0-9]{1,}', 'item', $k); // replace numeric key in array to 'data'
$this->xml .= "<$tag>";
$this->struct_xml($v);
$this->xml .= "</$tag>";
} else {
$tag = ereg_replace('^[0-9]{1,}', 'item', $k); // replace numeric key in array to 'data'
$this->xml .= "<$tag><![CDATA[$v]]></$tag>";
}
}
}
public function get_xml()
{
$header = "<?xml version=\"1.0\" encoding=\"" . $this->charset . "\"?><" . $this->root_name . ">";
$footer = "</" . $this->root_name . ">";
return $header . $this->xml . $footer;
}
}
I hope it helps to all.
This is best answered here Question 211383
These days, any self-respecting person should be using the stated "micro-clearfix" approach of clearing floats.
If you want it to be more generic and independent, you can use cookie. Iframe content can set a cookie. With jquery.cookie and a timer (or in this case javascript timer), you can check if the cookie is set each second or so.
//token should be a unique random value which is also sent to ifame to get set
iframeLoadCheckTimer = window.setInterval(function () {
cookieValue = $.cookie('iframeToken');
if (cookieValue == token)
{
window.clearInterval(iframeLoadCheckTimer );
$.cookie('iframeToken', null, {
expires: 1,
path: '/'
});
}
}, 1000);
I was looking for caching for my phonegap app storage and I found the answer of @TecHunter which is great but done using localCache
.
I found and come to know that localStorage is another alternative to cache the data returned by ajax call. So, I created one demo using localStorage
which will help others who may want to use localStorage
instead of localCache
for caching.
Ajax Call:
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: url,
data: '{"Id":"' + Id + '"}',
cache: true, //It must "true" if you want to cache else "false"
//async: false,
success: function (data) {
var resData = JSON.parse(data);
var Info = resData.Info;
if (Info) {
customerName = Info.FirstName;
}
},
error: function (xhr, textStatus, error) {
alert("Error Happened!");
}
});
To store data into localStorage:
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.cache) {
var success = originalOptions.success || $.noop,
url = originalOptions.url;
options.cache = false; //remove jQuery cache as we have our own localStorage
options.beforeSend = function () {
if (localStorage.getItem(url)) {
success(localStorage.getItem(url));
return false;
}
return true;
};
options.success = function (data, textStatus) {
var responseData = JSON.stringify(data.responseJSON);
localStorage.setItem(url, responseData);
if ($.isFunction(success)) success(responseJSON); //call back to original ajax call
};
}
});
If you want to remove localStorage, use following statement wherever you want:
localStorage.removeItem("Info");
Hope it helps others!
Json stands for JavaScript Object Notation really all json is are javascript objects so your array is in json form already. To write it out in a div you could do a bunch of things one of the easiest I think would be:
objectDiv.innerHTML = filter;
where objectDiv is the div you want selected from the DOM using jquery. If you wanted to list parts of the array out you could access them since it is a javascript object like so:
objectDiv.innerHTML = filter.dvals.valueToDisplay; //brand or count depending.
edit: anything you want to be a string but is not currently (which is rare javascript treats almost everything as a string) just use the toString()
function built in. so line above if you needed it would be filter.dvals.valueToDisplay.toString();
second edit to clarify: this answer is in response to the OP's comments and not completely to his original question.
For what it's worth, I hit a similar error in XCode 9.0.1. I tried uninstalling and reinstalling all my certs, but when I reinstalled, they seemed to remember the trust setting I had previously. What ended up working for me (it seems) was turning off the 'Always Trust' setting of the "Apple Worldwide Developer Relations Certification Authority" cert followed by a reboot. What a cryptic issue!
I needed to do this just now and required a cross-platform solution that was suitable for c++11, boost and openssl. I took D'Nabre's solution as a starting point and boiled it down to the following:
#include <openssl/md5.h>
#include <iomanip>
#include <sstream>
#include <boost/iostreams/device/mapped_file.hpp>
const std::string md5_from_file(const std::string& path)
{
unsigned char result[MD5_DIGEST_LENGTH];
boost::iostreams::mapped_file_source src(path);
MD5((unsigned char*)src.data(), src.size(), result);
std::ostringstream sout;
sout<<std::hex<<std::setfill('0');
for(auto c: result) sout<<std::setw(2)<<(int)c;
return sout.str();
}
A quick test executable demonstrates:
#include <iostream>
int main(int argc, char *argv[]) {
if(argc != 2) {
std::cerr<<"Must specify the file\n";
exit(-1);
}
std::cout<<md5_from_file(argv[1])<<" "<<argv[1]<<std::endl;
return 0;
}
Some linking notes:
Linux: -lcrypto -lboost_iostreams
Windows: -DBOOST_ALL_DYN_LINK libeay32.lib ssleay32.lib
$('#abc').css({"display":"none"});
this hides the content and also does not leave empty space.
I also had the same issue and I do not have .gitignore file. My problem was solved with the following way. This took all sub-directories and files.
git add <directory>/*
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
There are four cases.
:focus
(without active).:active
(without focus).:active:focus
(active and focus simultaneously).Example:
<div>
I cannot be focused.
</div>
<div tabindex="0">
I am focusable.
</div>
div:focus {
background: green;
}
div:active {
color: orange;
}
div:focus:active {
font-weight: bold;
}
When the page loads both are in case 1. When you press tab you will focus the second div and see it exhibit case 2. When you click on the first div you see case 3. When you click the second div, you see case 4.
Whether an element is focusable or not is another question. Most are not by default. But, it's safe to assume <a>
, <input>
, <textarea>
are focusable by default.
SELECT Top 1 sysobjects.[name], max(sysindexes.[rows]) AS TableRows,
CAST(
CASE max(sysindexes.[rows])
WHEN 0 THEN -0
ELSE LOG10(max(sysindexes.[rows]))
END
AS NUMERIC(5,2))
AS L10_TableRows
FROM sysindexes INNER JOIN sysobjects ON sysindexes.[id] = sysobjects.[id]
WHERE sysobjects.xtype = 'U'
GROUP BY sysobjects.[name]
ORDER BY max(rows) DESC
maybe your script tab has some problem.
if you set type, must type="application/javascript".
<!DOCTYPE html>
<html>
<head>
<title>
Hello
</title>
</head>
<body>
<div onclick="showMsg('Hello')">
Click me show message
</div>
<script type="application/javascript">
function showMsg(item) {
alert(item);
}
</script>
</body>
</html>
You would use the Console class
char[] password = console.readPassword("Enter password");
Arrays.fill(password, ' ');
By executing readPassword echoing is disabled. Also after the password is validated it is best to overwrite any values in the array.
If you run this from an ide it will fail, please see this explanation for a thorough answer: Explained
The usual pattern is EXISTS(subselect)
:
BEGIN
IF EXISTS(SELECT name
FROM test_table t
WHERE t.id = x
AND t.name = 'test')
THEN
---
ELSE
---
END IF;
This pattern is used in PL/SQL, PL/pgSQL, SQL/PSM, ...
**just fire bootstrap modal close button click event**
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope,$http){
$('#btnClose').click();// this is bootstrap modal close button id that fire click event
})
--------------------------------------------------------------------------------
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
just set modal 'close button' id as i set btnClose, for closing modal in angular you have to just fire that close button click event as i did $('#btnClose').click()
@RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
public @ResponseBody Object jsongStrImage(@RequestParam(value="image") MultipartFile image, @RequestParam String jsonStr) {
-- use com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
}
Either encode the needed XML entities or use CDATA.
<arg0>
<!--Optional:-->
<parameter1><test>like this</test></parameter1>
<!--Optional:-->
<parameter2><![CDATA[<test>or like this</test>]]></parameter2>
</arg0>
type C:\temp\test.bat>C:\temp\test.log
var json=[{"id":"431","code":"0.85.PSFR01215","price":"2457.77","volume":"23.0","total":"565.29"},{"id":"430","code":"0.85.PSFR00608","price":"1752.45","volume":"4.0","total":"70.1"},{"id":"429","code":"0.84.SMAB00060","price":"4147.5","volume":"2.0","total":"82.95"},{"id":"428","code":"0.84.SMAB00050","price":"4077.5","volume":"3.0","total":"122.32"}]
var obj = JSON.parse(json);
var length = Object.keys(obj).length; //you get length json result 4
Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.
As noted in the comments, when you loop over a list with something like for member in my_list
the member
variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:
my_list = [1,2,3]
for member in my_list:
member = 42
print my_list
Output:
[1, 2, 3]
If you want to change a list containing immutable types, you need to do something like:
my_list = [1,2,3]
for ndx, member in enumerate(my_list):
my_list[ndx] += 42
print my_list
Output:
[43, 44, 45]
If your list contains mutable objects, you can modify the current member
object directly:
class C:
def __init__(self, n):
self.num = n
def __repr__(self):
return str(self.num)
my_list = [C(i) for i in xrange(3)]
for member in my_list:
member.num += 42
print my_list
[42, 43, 44]
Note that you are still not changing the list, simply modifying the objects in the list.
You might benefit from reading Naming and Binding.
As stated (or at least alluded to) in many of the wonderful answers already given, this problem is easily solved once you have a set of numbers to work with.
Note: The following is T-SQL but it's simply my particular implementation of general concepts already mentioned here and on the internet at large. It should be relatively simple to convert the code to your dialect of choice.
How? Consider this query:
SELECT DATEADD(d, N, '0001-01-22')
FROM Numbers -- A table containing the numbers 0 through N
WHERE N <= 5;
The above produces the date range 1/22/0001 - 1/27/0001 and is extremely trivial. There are 2 key pieces of information in the above query: the start date of 0001-01-22
and the offset of 5
. If we combine these two pieces of information then we obviously have our end date. Thus, given two dates, generating a range can be broken down like so:
Find the difference between two given dates (the offset), easy:
-- Returns 125
SELECT ABS(DATEDIFF(d, '2014-08-22', '2014-12-25'))
Using ABS()
here ensures that the date order is irrelevant.
Generate a limited set of numbers, also easy:
-- Returns the numbers 0-2
SELECT N = ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) - 1
FROM(SELECT 'A' AS S UNION ALL SELECT 'A' UNION ALL SELECT 'A')
Notice we don't actually care what we're selecting FROM
here. We just need a set to work with so that we count the number of rows in it. I personally use a TVF, some use a CTE, others use a numbers table instead, you get the idea. I advocate for using the most performant solution that you also understand.
Combining these two methods will solve our problem:
DECLARE @date1 DATE = '9001-11-21';
DECLARE @date2 DATE = '9001-11-23';
SELECT D = DATEADD(d, N, @date1)
FROM (
SELECT N = ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) - 1
FROM (SELECT 'A' AS S UNION ALL SELECT 'A' UNION ALL SELECT 'A') S
) Numbers
WHERE N <= ABS(DATEDIFF(d, @date1, @date2));
The above example is horrible code but demonstrates how everything comes together.
More Fun
I need to do this kind of thing a lot so I encapsulated the logic into two TVFs. The first generates a range of numbers and the second uses this functionality to generate a range of dates. The math is to ensure that input order doesn't matter and because I wanted to use the full range of numbers available in GenerateRangeSmallInt
.
The following function takes ~16ms of CPU time to return the maximum range of 65536 dates.
CREATE FUNCTION dbo.GenerateRangeDate (
@date1 DATE,
@date2 DATE
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
SELECT D = DATEADD(d, N + 32768, CASE WHEN @date1 <= @date2 THEN @date1 ELSE @date2 END)
FROM dbo.GenerateRangeSmallInt(-32768, ABS(DATEDIFF(d, @date1, @date2)) - 32768)
);
GO
CREATE FUNCTION dbo.GenerateRangeSmallInt (
@num1 SMALLINT = -32768
, @num2 SMALLINT = 32767
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
WITH Numbers(N) AS (
SELECT N FROM(VALUES
(1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 16
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 32
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 48
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 64
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 80
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 96
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 112
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 128
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 144
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 160
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 176
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 192
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 208
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 224
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 240
, (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1), (1) -- 256
) V (N)
)
SELECT TOP(ABS(CAST(@num1 AS INT) - CAST(@num2 AS INT)) + 1)
N = ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) + CASE WHEN @num1 <= @num2 THEN @num1 ELSE @num2 END - 1
FROM Numbers A
, Numbers B
);
Yes! Finally! I just tried it with Chrome, Version 66.0.3359.170 (Official Build) (64-bit) on Mac.
You can change the values in the scopes as in the first picture, or with the console as in the second picture.
First of all, thank you all for your inputs. I tweak my Query - 1
and got my desired result. Gordon Linoff is right, PRINT
was messing up my query so I modified it as following:
Modified Query - 1:
SET ROWCOUNT 5
WHILE (1 = 1)
BEGIN
BEGIN TRANSACTION
UPDATE TableName
SET Value = 'abc1'
WHERE Parameter1 = 'abc' AND Parameter2 = 123
IF @@ROWCOUNT = 0
BEGIN
COMMIT TRANSACTION
BREAK
END
COMMIT TRANSACTION
END
SET ROWCOUNT 0
Output:
(5 row(s) affected)
(5 row(s) affected)
(4 row(s) affected)
(0 row(s) affected)
Selects a subset of the array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.
db.test.aggregate([
{$match: {"list.a": {$gt:3}}}, // <-- match only the document which have a matching element
{$project: {
list: {$filter: {
input: "$list",
as: "list",
cond: {$gt: ["$$list.a", 3]} //<-- filter sub-array based on condition
}}
}}
]);
Here is my method for getting dates between two dates, including / w.o. including business days. It also takes source and desired date format as parameter.
public static List<String> getAllDatesBetweenTwoDates(String stdate,String enddate,String givenformat,String resultformat,boolean onlybunessdays) throws ParseException{
DateFormat sdf;
DateFormat sdf1;
List<Date> dates = new ArrayList<Date>();
List<String> dateList = new ArrayList<String>();
SimpleDateFormat checkformat = new SimpleDateFormat(resultformat);
checkformat.applyPattern("EEE"); // to get Day of week
try{
sdf = new SimpleDateFormat(givenformat);
sdf1 = new SimpleDateFormat(resultformat);
stdate=sdf1.format(sdf.parse(stdate));
enddate=sdf1.format(sdf.parse(enddate));
Date startDate = (Date)sdf1.parse( stdate);
Date endDate = (Date)sdf1.parse( enddate);
long interval = 24*1000 * 60 * 60; // 1 hour in millis
long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
for(int i=0;i<dates.size();i++){
Date lDate =(Date)dates.get(i);
String ds = sdf1.format(lDate);
if(onlybunessdays){
String day= checkformat.format(lDate);
if(!day.equalsIgnoreCase("Sat") && !day.equalsIgnoreCase("Sun")){
dateList.add(ds);
}
}else{
dateList.add(ds);
}
//System.out.println(" Date is ..." + ds);
}
}catch(ParseException e){
e.printStackTrace();
throw e;
}finally{
sdf=null;
sdf1=null;
}
return dateList;
}
And the method call would be like :
public static void main(String aregs[]) throws Exception {
System.out.println(getAllDatesBetweenTwoDates("2015/09/27","2015/10/05","yyyy/MM/dd","dd-MM-yyyy",false));
}
You can find the demo code : Click Here
It depends how many times you're going to want to find this information, if more than once:
Set<Boolean> flags = new HashSet<Boolean>(myArray);
flags.contains(false);
Otherwise a short circuited loop:
for (i = 0; i < myArray.length; i++) {
if (!myArray[i]) return false;
}
return true;
It is working you have to check attr after assigning value
$('#amount').attr( 'datamin','1000');
alert($('#amount').attr( 'datamin'));?
My issue was the following error on windows 7:
C:\dev\Android\android-sdk-windows\tools>android
[INFO] Starting Android SDK and AVD Manager
No command line parameters provided, launching UI.
See 'android --help' for operations from the command line.
Exception in thread "main" java.lang.UnsatisfiedLinkError: no swt-win32-3550 or
swt-win32 in swt.library.path, java.library.path or the jar file
at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source)
at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source)
at org.eclipse.swt.internal.C.<clinit>(Unknown Source)
at org.eclipse.swt.widgets.Display.<clinit>(Unknown Source)
at com.android.sdkmanager.Main.showMainWindow(Main.java:292)
at com.android.sdkmanager.Main.doAction(Main.java:276)
at com.android.sdkmanager.Main.run(Main.java:99)
at com.android.sdkmanager.Main.main(Main.java:88)
The solution was to disable McAfee 8.8. Apparently some recent update is now blocking my Android environment.
We can also use space in a char class, in an expression similar to one of these:
(?!^[ ]*$)^\S+$
(?!^[ ]*$)^\S{1,}$
(?!^[ ]{0,}$)^\S{1,}$
(?!^[ ]{0,1}$)^\S{1,}$
depending on the language/flavor that we might use.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(?!^[ ]*$)^\S+$";
string input = @"
abcd
ABCD1234
#$%^&*()_+={}
abc def
ABC 123
";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
jex.im visualizes regular expressions:
I was having a hard time finding a way to actually separate the dollar amount and the amount after the decimal. I think I figured it out mostly and thought to share if any of yall were having trouble
So basically...
if price is 1234.44... whole would be 1234 and decimal would be 44 or
if price is 1234.01... whole would be 1234 and decimal would be 01 or
if price is 1234.10... whole would be 1234 and decimal would be 10
and so forth
$price = 1234.44;
$whole = intval($price); // 1234
$decimal1 = $price - $whole; // 0.44000000000005 uh oh! that's why it needs... (see next line)
$decimal2 = round($decimal1, 2); // 0.44 this will round off the excess numbers
$decimal = substr($decimal2, 2); // 44 this removed the first 2 characters
if ($decimal == 1) { $decimal = 10; } // Michel's warning is correct...
if ($decimal == 2) { $decimal = 20; } // if the price is 1234.10... the decimal will be 1...
if ($decimal == 3) { $decimal = 30; } // so make sure to add these rules too
if ($decimal == 4) { $decimal = 40; }
if ($decimal == 5) { $decimal = 50; }
if ($decimal == 6) { $decimal = 60; }
if ($decimal == 7) { $decimal = 70; }
if ($decimal == 8) { $decimal = 80; }
if ($decimal == 9) { $decimal = 90; }
echo 'The dollar amount is ' . $whole . ' and the decimal amount is ' . $decimal;
You don't need a batch file, just do this from powershell :
powershell -C "gci | % {rni $_.Name ($_.Name -replace 'Vacation2010', 'December')}"
Here's another example, showing that operator[]
overwrites the value for the key if it exists, but .insert
does not overwrite the value if it exists.
void mapTest()
{
map<int,float> m;
for( int i = 0 ; i <= 2 ; i++ )
{
pair<map<int,float>::iterator,bool> result = m.insert( make_pair( 5, (float)i ) ) ;
if( result.second )
printf( "%d=>value %f successfully inserted as brand new value\n", result.first->first, result.first->second ) ;
else
printf( "! The map already contained %d=>value %f, nothing changed\n", result.first->first, result.first->second ) ;
}
puts( "All map values:" ) ;
for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )
printf( "%d=>%f\n", iter->first, iter->second ) ;
/// now watch this..
m[5]=900.f ; //using operator[] OVERWRITES map values
puts( "All map values:" ) ;
for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )
printf( "%d=>%f\n", iter->first, iter->second ) ;
}
Another way is to use np.place
which does in-place replacement and works with multidimentional arrays:
import numpy as np
# create 2x3 array with numbers 0..5
arr = np.arange(6).reshape(2, 3)
# replace 0 with -10
np.place(arr, arr == 0, -10)
Either KeyDown or KeyUp.
TextBox tb = new TextBox();
tb.KeyDown += new KeyEventHandler(tb_KeyDown);
static void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//enter key is down
}
}
You don't need to create the SSH keys on the Jenkins server, nor do you need to store the SSH keys on the Jenkins server's filesystem. This bit of information is crucial in environments where Jenkins servers instances may be created and destroyed frequently.
On any machine (Windows, Linux, MacOS ...doesn't matter) generate an SSH key pair. Use this article as guide:
On the target server, you will need to place the content of the public key (id_rsa.pub
per the above article) into the .ssh/authorized_keys
file under the home directory of the user which Jenkins will be using for deployment.
Ref: https://plugins.jenkins.io/publish-over-ssh/
Visit: Jenkins
> Manage Jenkins
> Configure System
> Publish over SSH
id_rsa
per the above article) into the "Key" fieldVisit: Jenkins
> Credentials
> System
> Global credentials (unrestricted)
> Add Credentials
id_rsa
per the above article)]You can also have several workspaces - so you can connect to one and have set "A" of projects - and then connect to a different set when ever you like.
public class MainClass {
public static void main(String args[]) {
System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);
System.out.printf("Default floating-point format: %f\n", 1234567.123);
System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);
System.out.printf("Line-up positive and negative values:\n");
System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
}
}
And print out:
3 (3) +3 00003
Default floating-point format: 1234567,123000
Floating-point with commas: 1.234.567,123000
Negative floating-point default: -1.234.567,123000
Negative floating-point option: (1.234.567,123000)Line-up positive and negative values:
1.234.567,12
-1.234.567,12
Ok, so I had the same problem and found a solution in a udacity forum:
In Android Studio:
@Mark Cidade
Thanks Mark! This solved few days of research on wondering how should I call this from the PHP WshShell. So thanks to your code, I figured...
function __exec($tmppath, $cmd)
{
$WshShell = new COM("WScript.Shell");
$tmpf = rand(1000, 9999).".tmp"; // Temp file
$tmpfp = $tmppath.'/'.$tmpf; // Full path to tmp file
$oExec = $WshShell->Run("cmd /c $cmd -c ... > ".$tmpfp, 0, true);
// return $oExec == 0 ? true : false; // Return True False after exec
return $tmpf;
}
This is what worked for me in my case. Feel free to use and modify as per your needs. You can always add functionality within the function to automatically read the tmp file, assign it to a variable and/or return it and then delete the tmp file. Thanks again @Mark!
Here's a way to convert binary numbers to ASCII characters that is often simple enough to do in your head.
1 - Convert every 4 binary digits into one hex digit.
Here's a binary to hex conversion chart:
0001 = 1
0010 = 2
0011 = 3
0100 = 4
0101 = 5
0110 = 6
0111 = 7
1000 = 8
1001 = 9
1010 = a (the hex number a, not the letter a)
1011 = b
1100 = c
1101 = d
1110 = e
1111 = f
(The hexadecimal numbers a through f are the decimal numbers 10 through 15. That's what hexadecimal, or "base 16" is - instead of each digit being capable of representing 10 different numbers [0 - 9], like decimal or "base 10" does, each digit is instead capable of representing 16 different numbers [0 - f].)
Once you know that chart, converting any string of binary digits into a string of hex digits is simple.
For example,
01000100 = 0100 0100 = 44 hex
1010001001110011 = 1010 0010 0111 0011 = a273 hex
Simple enough, right? It is a simple matter to convert a binary number of any length into its hexadecimal equivalent.
(This works because hexadecimal is base 16 and binary is base 2 and 16 is the 4th power of 2, so it takes 4 binary digits to make 1 hex digit. 10, on the other hand, is not a power of 2, so we can't convert binary to decimal nearly as easily.)
2 - Split the string of hex digits into pairs.
When converting a number into ASCII, every 2 hex digits is a character. So break the hex string into sets of 2 digits.
You would split a hex number like 7340298b392 this into 6 pairs, like this:
7340298b392 = 07 34 02 98 b3 92
(Notice I prepended a 0, since I had an odd number of hex digits.)
That's 6 pairs of hex digits, so its going to be 6 letters. (Except I know right away that 98, b3 and 92 aren't letters. I'll explain why in a minute.)
3 - Convert each pair of hex digits into a decimal number.
Do this by multiplying the (decimal equivalent of the) left digit by 16, and adding the 2nd.
For example, b3 hex = 11*16 + 3, which is 110 + 66 + 3, which is 179. (b hex is 11 decimal.)
4 - Convert the decimal numbers into ASCII characters.
Now, to get the ASCII letters for the decimal numbers, simply keep in mind that in ASCII, 65 is an uppercase 'A', and 97 is a lowercase 'a'.
So what letter is 68?
68 is the 4th letter of the alphabet in uppercase, right?
65 = A, 66 = B, 67 = C, 68 = D.
So 68 is 'D'.
You take the decimal number, subtract 64 for uppercase letters if the number is less than 97, or 96 for lowercase letters if the number is 97 or larger, and that's the number of the letter of the alphabet associated with that set of 2 hex digits.
Alternatively, if you're not afraid of a little bit of easy hex arithmetic, you can skip step 3, and just go straight from hex to ASCII, by remembering, for example, that
hex 41 = 'A'
hex 61 = 'a'
So subtract 40 hex for uppercase letters or 60 hex for lowercase letters, and convert what's left to decimal to get the alphabet letter number.
For example
01101100 = 6c, 6c - 60 = c = 12 decimal = 'l'
01010010 = 52, 52 - 40 = 12 hex = 18 decimal = 'R'
(When doing this, it's helpful to remember that 'm' (or 'M') is the 13 letter of the alphabet. So you can count up or down from 13 to find a letter that's nearer to the middle than to either end.)
I saw this on a shirt once, and was able to read it in my head:
01000100
01000001
01000100
I did it like this:
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
01000001 = 0100 0001 = 41 hex, - 40 hex = ucase letter 1 = A
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
The shirt said "DAD", which I thought was kinda cool, since it was being purchased by a pregnant woman. Her husband must be a geek like me.
How did I know right away that 92, b3, and 98 were not letters?
Because the ASCII code for a lowercase 'z' is 96 + 26 = 122, which in hex is 7a. 7a is the largest hex number for a letter. Anything larger than 7a is not a letter.
So that's how you can do it as a human.
How do computer programs do it?
For each set of 8 binary digits, convert it to a number, and look it up in an ASCII table.
(That's one pretty obvious and straight forward way. A typical programmer could probably think of 10 or 15 other ways in the space of a few minutes. The details depend on the computer language environment.)
If you using latest Owl Carousel 2 version. You can replace the Navigation text by fontawesome icon. Code is below.
$('.your-class').owlCarousel({
loop: true,
items: 1, // Select Item Number
autoplay:true,
dots: false,
nav: true,
navText: ["<i class='fa fa-long-arrow-left'></i>","<i class='fa fa-long-arrow-right'></i>"],
});
^([+-]?[0-9]\d*|0)$
will accept numbers with leading "+", leading "-" and leadings "0"
You have the right idea, as documentation shows:
http://docs.jquery.com/CSS/css#namevalue
Are you sure you're correctly identify this with class or id?
For example, if your class is myElementClass
$('.myElementClass').css('text-align','center');
Also, I haven't worked with Firebug in a while, but are you looking at the dom and not the html? Your source isn't changed by javascript, but the dom is. Look in the dom tab and see if the change was applied.
Truth be told there are many, many resources explaining how to do this already out on the web:
Git: how to reverse-merge a commit?
Git: how to reverse-merge a commit?
Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)
So I guess I'll just summarize some of these:
git revert <merge commit hash>
This creates an extra "revert" commit saying you undid a merge
git reset --hard <commit hash *before* the merge>
This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick
them on to afterwards.
But honestly this guide here is better than anything I can explain, with diagrams! :)
If you just have a Python shell running, type:
import idlelib.PyShell
idlelib.PyShell.main()
you can use this:
try {
Intent followIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" +
"https://www.facebook.com/app_scoped_user_id/"+scoped user id+"/"));
activity.startActivity(followIntent);
} catch (Exception e) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + user name)));
String errorMessage = (e.getMessage() == null) ? "Message is empty" : e.getMessage();
}
attention: you can get scoped user id from "link" permission facebook api
According to MDN, "matchMedia" is the proper way to do this https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#Monitoring_screen_resolution_or_zoom_level_changes
it's a bit finicky because each instance can only watch one MQ at a time, so if you're interested in any zoom level change you need to make a bunch of matchers.. but since the browser is in charge to emitting the events it's probably still more performant than polling, and you could throttle or debounce the callback or pin it to an animation frame or something - here's an implementation that seems pretty snappy, feel free to swap in _throttle or whatever if you're already depending on that.
Run the code snippet and zoom in and out in your browser, note the updated value in the markup - I only tested this in Firefox! lemme know if you see any issues.
const el = document.querySelector('#dppx')_x000D_
_x000D_
if ('matchMedia' in window) {_x000D_
function observeZoom(cb, opts) {_x000D_
opts = {_x000D_
// first pass for defaults - range and granularity to capture all the zoom levels in desktop firefox_x000D_
ceiling: 3,_x000D_
floor: 0.3,_x000D_
granularity: 0.05,_x000D_
...opts_x000D_
}_x000D_
const precision = `${opts.granularity}`.split('.')[1].length_x000D_
_x000D_
let val = opts.floor_x000D_
const vals = []_x000D_
while (val <= opts.ceiling) {_x000D_
vals.push(val)_x000D_
val = parseFloat((val + opts.granularity).toFixed(precision))_x000D_
}_x000D_
_x000D_
// construct a number of mediamatchers and assign CB to all of them_x000D_
const mqls = vals.map(v => matchMedia(`(min-resolution: ${v}dppx)`))_x000D_
_x000D_
// poor person's throttle_x000D_
const throttle = 3_x000D_
let last = performance.now()_x000D_
mqls.forEach(mql => mql.addListener(function() {_x000D_
console.debug(this, arguments)_x000D_
const now = performance.now()_x000D_
if (now - last > throttle) {_x000D_
cb()_x000D_
last = now_x000D_
}_x000D_
}))_x000D_
}_x000D_
_x000D_
observeZoom(function() {_x000D_
el.innerText = window.devicePixelRatio_x000D_
})_x000D_
} else {_x000D_
el.innerText = 'unable to observe zoom level changes, matchMedia is not supported'_x000D_
}
_x000D_
<div id='dppx'>--</div>
_x000D_
clipboard
There is a special register for storing this selection, it is the "* register. Nothing is put in here unless the information about what text is selected is about to change (e.g. with a left mouse click somewhere), or when another application wants to paste the selected text. Then the text is put in the "* register. For example, to cut a line and make it the current selection/put it on the CLIPBOARD:
"*dd
Similarly, when you want to paste a selection from another application, e.g., by clicking the middle mouse button, the selection is put in the "* register first, and then 'put' like any other register. For example, to put the selection (contents of the CLIPBOARD):
"*p
registers E354
> There are nine types of registers:
> 1. The unnamed register ""
> 2. 10 numbered registers "0 to "9
> 3. The small delete register "-
> 4. 26 named registers "a to "z or "A to "Z
> 5. four read-only registers ":, "., "% and "#
> 6. the expression register "=
> 7. The selection and drop registers "*, "+ and "~
> 8. The black hole register "_
> 9. Last search pattern register "/
Paste from clipboard
1. Clipboard: Copy
2. Vim insertmode, middle mouse key
Check for X11-clipboard support in terminal
When you like to run Vim in a terminal you need to look for a version of Vim that was compiled with clipboard support. Check for X11-clipboard support, from the console, type:
% vim --version
If you see "+xterm_clipboard", you are good to go.
http://vim.wikia.com/wiki/Accessing_the_system_clipboard
The X server maintains three selections, called:
PRIMARY, SECONDARY and CLIPBOARD
The PRIMARY selection is conventionally used to implement copying and pasting via the middle mouse button. The SECONDARY and CLIPBOARD selections are less frequently used by application programs.
The accepted answer doesn't work for multi-line text.
I updated the JSfiddle to show CSS multiline text vertical align as explained here:
<div id="column-content">
<div>yet another text content that should be centered vertically</div>
</div>
#column-content {
border: 1px solid red;
height: 200px;
width: 100px;
}
div {
display: table-cell;
vertical-align:middle;
text-align: center;
}
It also works with <br />
in "yet another..."
Here is my modification of @rashy above. The script does the following:
This is the script:
@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"="
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"
IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop
:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END
:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
set LIST=(diqc.oca wiki.oca)
::Set the ip of the domains you set in the list above
set diqc.oca=192.168.111.6
set wiki.oca=192.168.111.4
:: deletes the parentheses from LIST
set _list=%LIST:~1,-1%
::ECHO %WINDIR%\System32\drivers\etc\hosts > tmp.txt
for %%G in (%_list%) do (
set _name=%%G
set _value=!%%G!
SET NEWLINE=^& echo.
ECHO Carrying out requested modifications to your HOSTS file
::strip out this specific line and store in tmp file
type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_name! > tmp.txt
::re-add the line to it
ECHO %NEWLINE%^!_value! !_name!>>tmp.txt
::overwrite host file
copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts
del tmp.txt
)
ipconfig /flushdns
ECHO.
ECHO.
ECHO Finished, you may close this window now.
ECHO You should now open Chrome and go to "chrome://net-internals/#dns" (without quotes)
ECHO then click the "clear host cache" button
GOTO END
:END
ECHO.
ping -n 11 192.0.2.2 > nul
EXIT
I don't know of a way to do that (you can get the language and try to deduct the locale from that).
I tried to cook a little something to try and do that (only tested on Firefox with one locale). should work as long as the short date string includes the date as digits, so it might fail for, say, arabic. It might have other bugs too, i don't know all the different locales peculiarities, this is just a concept...
function getShortDateFormat() {
var d = new Date(1992, 0, 7);
var s = d.toLocaleDateString();
function formatReplacer(str) {
var num = parseInt(str);
switch (num % 100) {
case 92:
return str.replace(/.{1}/g, "Y");
case 1:
return str.length == 1 ? "mM" : "MM"
case 7:
return str.length == 1 ? "dD" : "DD"
}
}
shortDateFormat = s.replace(/\d+/g, formatReplacer);
return shortDateFormat;
}
getShortDateFormat();
The outputted format will be:
So in my browser, the shortDateformat you get is "MM/DD/YYYY".
For Bootstrap 3, there is
placement: 'auto right'
which is easier. By default, it will be right, but if the element is located in the right side of the screen, the popover will be left. So it should be:
$('.infopoint').popover({
trigger:'hover',
animation: false,
placement: 'auto right'
});
I am not for throwing Exceptions in the constructor since I am considering this as non-clean. There are several reasons for my opinion.
As Richard mentioned you cannot initialize an instance in an easy manner. Especially in tests it is really annoying to build a test-wide object only by surrounding it in a try-catch during initialization.
Constructors should be logic-free. There is no reason at all to encapsulate logic in a constructor, since you are always aiming for the Separation of Concerns and Single Responsibility Principle. Since the concern of the constructor is to "construct an object" it should not encapsulate any exception handling if following this approach.
It smells like bad design. Imho if I am forced to do exception handling in the constructor I am at first asking myself if I have any design frauds in my class. It is necessary sometimes, but then I outsource this to a builder or factory to keep the constructor as simple as possible.
So if it is necessary to do some exception handling in the constructor, why would you not outsource this logic to a Builder of Factory? It might be a few more lines of code but gives you the freedom to implement a far more robust and well suited exception handling since you can outsource the logic for the exception handling even more and are not sticked to the constructor, which will encapsulate too much logic. And the client does not need to know anything about your constructing logic if you delegate the exception handling properly.
A possibility is that the git server you are pushing to is down/crashed, and the solution lies in restarting the git server.
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014
Just be sure to be using correct instance and connect each other
Just pay attention in Stored procs must be recompiled
If you getting an error like below
Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/<PackageName>/vendor'
I suggest using the below command to install your global package
sudo npm install -g <PackageName> --unsafe-perm=true --allow-root
Since this answer was somehow accepted and thus will appear at the top, although it's not the best, I've improved it based on the other answers and the comments.
The C way; simplest, but will treat any invalid number as 0:
#include <cstdlib>
int x = atoi(argv[1]);
The C way with input checking:
#include <cstdlib>
errno = 0;
char *endptr;
long int x = strtol(argv[1], &endptr, 10);
if (endptr == argv[1]) {
std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (*endptr) {
std::cerr << "Trailing characters after number: " << argv[1] << '\n';
} else if (errno == ERANGE) {
std::cerr << "Number out of range: " << argv[1] << '\n';
}
The C++ iostreams way with input checking:
#include <sstream>
std::istringstream ss(argv[1]);
int x;
if (!(ss >> x)) {
std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (!ss.eof()) {
std::cerr << "Trailing characters after number: " << argv[1] << '\n';
}
Alternative C++ way since C++11:
#include <stdexcept>
#include <string>
std::string arg = argv[1];
try {
std::size_t pos;
int x = std::stoi(arg, &pos);
if (pos < arg.size()) {
std::cerr << "Trailing characters after number: " << arg << '\n';
}
} catch (std::invalid_argument const &ex) {
std::cerr << "Invalid number: " << arg << '\n';
} catch (std::out_of_range const &ex) {
std::cerr << "Number out of range: " << arg << '\n';
}
All four variants assume that argc >= 2
. All accept leading whitespace; check isspace(argv[1][0])
if you don't want that. All except atoi
reject trailing whitespace.
My simple way, but it can help for further variations on this subject. List all methods and alter them to useless.
Object.getOwnPropertyNames(console).filter(function(property) {
return typeof console[property] == 'function';
}).forEach(function (verb) {
console[verb] =function(){return 'Sorry, for security reasons...';};
});
You could use moment.js with Postman to give you that timestamp format.
You can add this to the pre-request script:
const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));
Then reference {{today}}
where ever you need it.
If you add this to the Collection Level Pre-request Script
, it will be run for each request in the Collection
. Rather than needing to add it to all the requests individually.
For more information about using moment
in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/
Try this:
static void Main(string[] args)
{
var dt = new DataTable
{
Columns = { { "Lastname",typeof(string) }, { "Firstname",typeof(string) } }
};
dt.Rows.Add("Lennon", "John");
dt.Rows.Add("McCartney", "Paul");
dt.Rows.Add("Harrison", "George");
dt.Rows.Add("Starr", "Ringo");
List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList();
foreach(string e in s)
Console.WriteLine(e);
Console.ReadLine();
}
Use NSJSONSerialization:
NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
options:NSJSONReadingAllowFragments
error:&error];
The latest returns id
, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).
Here is a small function I wrote to try all the colorschemes in $VIMRUNTIME/colors directory.
Add the below function to your vimrc, then open your source file and call the function from command.
function! DisplayColorSchemes()
let currDir = getcwd()
exec "cd $VIMRUNTIME/colors"
for myCol in split(glob("*"), '\n')
if myCol =~ '\.vim'
let mycol = substitute(myCol, '\.vim', '', '')
exec "colorscheme " . mycol
exec "redraw!"
echo "colorscheme = ". myCol
sleep 2
endif
endfor
exec "cd " . currDir
endfunction
this is output of this program
Scanner s=new Scanner (System.in);
int row, elem, col;
Systm.out.println("Enter Element to insert");
elem = s.nextInt();
System.out.println("Enter row");
row=s.nextInt();
System.out.println("Enter row");
col=s.nextInt();
for (int c=row-1; c < row; c++)
{
for (d = col-1 ; d < col ; d++)
array[c][d] = elem;
}
for(c = 0; c < size; c++)
{
for (d = 0 ; d < size ; d++)
System.out.print( array[c] [d] +" ");
System.out.println();
}
There are 5 cases for using the underscore in Python.
For storing the value of last expression in interpreter.
For ignoring the specific values. (so-called “I don’t care”)
To give special meanings and functions to name of variables or functions.
To use as ‘internationalization (i18n)’ or ‘localization (l10n)’ functions.
To separate the digits of number literal value.
Here is a nice article with examples by mingrammer.
/*
* convert server time to local time
* simbu
*/
function convertTime(serverdate) {
var date = new Date(serverdate);
// convert to utc time
var toutc = date.toUTCString();
//convert to local time
var locdat = new Date(toutc + " UTC");
return locdat;
}
it also happens when you call a function from jsx directly rather than in an event. like
it will show the error if you write like
<h1>{this.myFunc}<h2>
it will go if you write:
<h1 onClick={this.myFunc}>Hit Me</h1>
Only downside (it seems), is that the table cell widths are identical. Any way to get around this? – Josh Stodola Oct 12 at 15:53
Just define width of the table and width for each table cell
something like
table {border-collapse:collapse; table-layout:fixed; width:900px;}
th {background: yellow; }
td {overflow:hidden;white-space:nowrap; }
.cells1{width:300px;}
.cells2{width:500px;}
.cells3{width:200px;}
It works like a charm :o)
using System.Globalization;
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00",
"s",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal, out d);
I think the simplest approach is using Object.assign
.
If you have this Class:
class MyHelper {
constructor(options) {
this.options = Object.assign({
name: "John",
surname: "Doe",
birthDate: "1980-08-08"
}, options);
}
}
You can use it like this:
let helper = new MyHelper({ name: "Mark" });
console.log(helper.options.surname); // this will output "Doe"
Documentation (with polyfill): https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
For nullable, use ?
with all of the C# primitives, except for string.
The following page gives a list of the C# primitives: http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx
This is an answered question, but I'll give my "one cent":
Business rules belong in the model. The "model" always consists of (logically or physically separated):
Business rules live in the domain model, are exposed in a presentation-suitable form to the "presentation" model and are sometimes duplicated (or also enforced) in the "data layer".
I solved the problem. In Home Ubuntu, I deleted the .gradle folder and downloaded it again. I hope it is useful
Because you're using multiple. Despite it still technically being a dropdown, it doesn't look or act like a standard dropdown. Rather, it populates a list box and lets them select multiple options.
Size determines how many options appear before they have to click down or up to see the other options.
I have a feeling what you want to achieve is only going to be possible with a JavaScript plugin.
Some examples:
jQuery multiselect drop down menu
http://labs.abeautifulsite.net/archived/jquery-multiSelect/demo/
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
Extern is the keyword you use to declare that the variable itself resides in another translation unit.
So you can decide to use a variable in a translation unit and then access it from another one, then in the second one you declare it as extern and the symbol will be resolved by the linker.
If you don't declare it as extern you'll get 2 variables named the same but not related at all, and an error of multiple definitions of the variable.
but i only wanted the for statement to be attached to the if statement, not the else if statements as well.
Well get rid of the else
then. If the else if
is not supposed to be part of the for
then write it as:
for(int i=0; i<something_in_the_array.length;i++)
if(whatever_value==(something_in_the_array[i]))
{
value=2;
break;
}
if(whatever_value==2)
{
value=3;
break; // redundant now
}
else if(whatever_value==3)
{
value=4;
break; // redundant now
}
Having said that:
else
part in the loop doesn't seem to make a lot of sense here,Finally, braces are less obtrusive if you put the opening brace on the end of the previous line; e.g.
if (something) {
doSomething();
}
rather than:
if (something)
{
doSomething();
}
This didn't work for me.
sudo chmod -R 777 /path/to/your/file/or/directory
I used -f
also.
sudo chmod -R -f 777 /path/to/your/file/or/directory
Similar to Julien's answer above, I had success with the following:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
This solution might be more relevant if you want more control in matlab.
Solution inspired by: https://stackoverflow.com/a/52526454/10521959
valentina-db it has free version for sql server
.rpm and .deb
serial id will be sent by email after registration
https://www.valentina-db.com/en/
You need 3 boundaries for inline images to be fully compliant.
Everything goes inside the multipart/mixed
.
Then use the multipart/related
to contain your multipart/alternative
and your image attachment headers.
Lastly, include your downloadable attachments inside the last boundary of multipart/mixed
.
If you are allowed to run real native binaries, then this is your compiler:
https://github.com/ircmaxell/php-compiler
It's a PHP compiler written in PHP!
It compiles PHP code to its own VM code. This VM code can then either be interpreted by its own interpreter (also written in PHP, isn't that crazy?) or it can be translated to Bitcode. And using the LLVM compiler framework (clang
and co), this Bitcode can be compiled into a native binary for any platform that LLVM supports (pretty much any platform that matters today). You can choose to either do that statically or each time just before the code is executed (JIT style). So the only two requirements for this compiler to work on your system is an installed PHP interpreter and an installed clang
compiler.
If you are not allowed to run native binaries, you could use the compiler above as an interpreter and let it interpret its own VM code, yet this will be slow as you are running a PHP interpreter that itself is running on a PHP engine, so you have a "double interpretation".
You cannot append to an existing xlsx file with xlsxwriter
.
There is a module called openpyxl which allows you to read and write to preexisting excel file, but I am sure that the method to do so involves reading from the excel file, storing all the information somehow (database or arrays), and then rewriting when you call workbook.close()
which will then write all of the information to your xlsx file.
Similarly, you can use a method of your own to "append" to xlsx documents. I recently had to append to a xlsx file because I had a lot of different tests in which I had GPS data coming in to a main worksheet, and then I had to append a new sheet each time a test started as well. The only way I could get around this without openpyxl was to read the excel file with xlrd and then run through the rows and columns...
i.e.
cells = []
for row in range(sheet.nrows):
cells.append([])
for col in range(sheet.ncols):
cells[row].append(workbook.cell(row, col).value)
You don't need arrays, though. For example, this works perfectly fine:
import xlrd
import xlsxwriter
from os.path import expanduser
home = expanduser("~")
# this writes test data to an excel file
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
sheet1 = wb.add_worksheet()
for row in range(10):
for col in range(20):
sheet1.write(row, col, "test ({}, {})".format(row, col))
wb.close()
# open the file for reading
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home))
sheets = wbRD.sheets()
# open the same file for writing (just don't write yet)
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
# run through the sheets and store sheets in workbook
# this still doesn't write to the file yet
for sheet in sheets: # write data from old file
newSheet = wb.add_worksheet(sheet.name)
for row in range(sheet.nrows):
for col in range(sheet.ncols):
newSheet.write(row, col, sheet.cell(row, col).value)
for row in range(10, 20): # write NEW data
for col in range(20):
newSheet.write(row, col, "test ({}, {})".format(row, col))
wb.close() # THIS writes
However, I found that it was easier to read the data and store into a 2-dimensional array because I was manipulating the data and was receiving input over and over again and did not want to write to the excel file until it the test was over (which you could just as easily do with xlsxwriter since that is probably what they do anyway until you call .close()
).
I rewritten a little the maklemenz's answer:
private static Method m;
static {
try {
m = Throwable.class.getDeclaredMethod(
"getStackTraceElement",
int.class
);
}
catch (final NoSuchMethodException e) {
throw new NoSuchMethodUncheckedException(e);
}
catch (final SecurityException e) {
throw new SecurityUncheckedException(e);
}
}
public static String getMethodName(int depth) {
StackTraceElement element;
final boolean accessible = m.isAccessible();
m.setAccessible(true);
try {
element = (StackTraceElement) m.invoke(new Throwable(), 1 + depth);
}
catch (final IllegalAccessException e) {
throw new IllegalAccessUncheckedException(e);
}
catch (final InvocationTargetException e) {
throw new InvocationTargetUncheckedException(e);
}
finally {
m.setAccessible(accessible);
}
return element.getMethodName();
}
public static String getMethodName() {
return getMethodName(1);
}
Here is a C function that handles positive OR negative integer OR fractional values for BOTH OPERANDS
#include <math.h>
float mod(float a, float N) {return a - N*floor(a/N);} //return in range [0, N)
This is surely the most elegant solution from a mathematical standpoint. However, I'm not sure if it is robust in handling integers. Sometimes floating point errors creep in when converting int -> fp -> int.
I am using this code for non-int s, and a separate function for int.
NOTE: need to trap N = 0!
Tester code:
#include <math.h>
#include <stdio.h>
float mod(float a, float N)
{
float ret = a - N * floor (a / N);
printf("%f.1 mod %f.1 = %f.1 \n", a, N, ret);
return ret;
}
int main (char* argc, char** argv)
{
printf ("fmodf(-10.2, 2.0) = %f.1 == FAIL! \n\n", fmodf(-10.2, 2.0));
float x;
x = mod(10.2f, 2.0f);
x = mod(10.2f, -2.0f);
x = mod(-10.2f, 2.0f);
x = mod(-10.2f, -2.0f);
return 0;
}
(Note: You can compile and run it straight out of CodePad: http://codepad.org/UOgEqAMA)
Output:
fmodf(-10.2, 2.0) = -0.20 == FAIL!
10.2 mod 2.0 = 0.2
10.2 mod -2.0 = -1.8
-10.2 mod 2.0 = 1.8
-10.2 mod -2.0 = -0.2
To calculate gradients, the machine learning community uses Autograd:
To install:
pip install autograd
Here is an example:
import autograd.numpy as np
from autograd import grad
def fct(x):
y = x**2+1
return y
grad_fct = grad(fct)
print(grad_fct(1.0))
It can also compute gradients of complex functions, e.g. multivariate functions.
As what Jakob said: windows sdk 7.1 cannot be installed if MS VC++ x64 and x86 runtimes and redisrtibutables of version 10.0.40219 are present. after removing them win sdk install is okay, VS C++ SP1 can be installed fine again.
Kind regards
Following examples work for me, please note "is_user_defined" NOT "is_table_type"
IF TYPE_ID(N'idType') IS NULL
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
IF not EXISTS (SELECT * FROM sys.types WHERE is_user_defined = 1 AND name = 'idType')
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
The certificate that you already have is probably the server's certificate, or the certificate used to sign the server's certificate. You will need it so that your web service client can authenticate the server.
But if additionally you need to perform client authentication with SSL, then you need to get your own certificate, to authenticate your web service client. For this you need to create a certificate request; the process involves creating your own private key, and the corresponding public key, and attaching that public key along with some of your info (email, name, domain name, etc) to a file that's called the certificate request. Then you send that certificate request to the company that's already asked you for it, and they will create your certificate, by signing your public key with their private key, and they'll send you back an X509 file with your certificate, which you can now add to your keystore, and you'll be ready to connect to a web service using SSL requiring client authentication.
To generate your certificate request, use "keytool -certreq -alias -file -keypass -keystore ". Send the resulting file to the company that's going to sign it.
When you get back your certificate, run "keytool -importcert -alias -keypass -keystore ".
You may need to used -storepass in both cases if the keystore is protected (which is a good idea).
Here's what I did that helped if you are specifically having a problem on Leopard.
My cert was old and needed to be updated. I downloaded this:
http://curl.haxx.se/ca/cacert.pem
Then replaced my cert which was found here on Leopard:
/usr/share/curl/curl-ca-bundle.crt
Reload whatever you have that's accessing it and you should be good to go!
Just create a new branch with git checkout -b ABC_1
; your uncommitted changes will be kept, and you then commit them to that branch.
to print only the certificate chain and not the server's certificate:
# MYHOST=myhost.com
# MYPORT=443
# openssl s_client -connect ${MYHOST}:${MYPORT} -showcerts 2>/dev/null </dev/null | awk '/^.*'"${MYHOST}"'/,/-----END CERTIFICATE-----/{next;}/-----BEGIN/,/-----END CERTIFICATE-----/{print}'
to update CA trust on CentOS/RHEL 6/7 :
# update-ca-trust enable
# openssl s_client -connect ${MYHOST}:${MYPORT} -showcerts 2>/dev/null </dev/null | awk '/^.*'"${MYHOST}"'/,/-----END CERTIFICATE-----/{next;}/-----BEGIN/,/-----END CERTIFICATE-----/{print}' >/etc/pki/ca-trust/source/anchors/myca.cert
# update-ca-trust extract
on CentOS/RHEL 5:
# openssl s_client -connect ${MYHOST}:${MYPORT} -showcerts 2>/dev/null </dev/null | awk '/^.*'"${MYHOST}"'/,/-----END CERTIFICATE-----/{next;}/-----BEGIN/,/-----END CERTIFICATE-----/{print}' >>/etc/pki/tls/certs/ca-bundle.crt
select View-->DBMS Output in menu and
When I had this problem, I had included the mail-api.jar
in my maven pom file. That's the API specification only. The fix is to replace this:
<!-- DO NOT USE - it's just the API, not an implementation -->
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
with the reference implementation of that api:
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
I know it has sun in the package name, but that's the latest version. I learned this from https://stackoverflow.com/a/28935760/1128668
Hope this easy one liner helps:
cols_as_np = df[df.columns[1:]].to_numpy()
It depends on where you're displaying the text. On the console or a textbox for example, \n will suffice. On a RichTextBox I think you need both.
Just adding some extra sorting if needed
=QUERY(A2:A,"select A, count(A) where A is not null group by A order by count(A) DESC label A 'Name', count(A) 'Count'",-1)
You could use the SQL%ROWCOUNT
Oracle variable:
UPDATE table1
SET field2 = value2,
field3 = value3
WHERE field1 = value1;
IF (SQL%ROWCOUNT = 0) THEN
INSERT INTO table (field1, field2, field3)
VALUES (value1, value2, value3);
END IF;
It would be easier just to determine if your primary key (i.e. field1
) has a value and then perform an insert or update accordingly. That is, if you use said values as parameters for a stored procedure.
It checks to see whether the specific object is contained in the list.
You might be better using the Find method on the list.
Here's an example
List<CartProduct> lst = new List<CartProduct>();
CartProduct objBeer;
objBeer = lst.Find(x => (x.Name == "Beer"));
Hope that helps
You should also look at LinQ - overkill for this perhaps, but a useful tool nonetheless...
Python is almost a functional language. It's "functional lite".
It has extra features, so it isn't pure enough for some.
It also lacks some features, so it isn't complete enough for some.
The missing features are relatively easy to write. Check out posts like this on FP in Python.
You need to add a CDATA tag inside of the script tag, unless you want to manually go through and escape all XHTML characters (e.g. &
would need to become &
). For example:
<script>
//<![CDATA[
var el = document.getElementById("pacman");
if (Modernizr.canvas && Modernizr.localstorage &&
Modernizr.audio && (Modernizr.audio.ogg || Modernizr.audio.mp3)) {
window.setTimeout(function () { PACMAN.init(el, "./"); }, 0);
} else {
el.innerHTML = "Sorry, needs a decent browser<br /><small>" +
"(firefox 3.6+, Chrome 4+, Opera 10+ and Safari 4+)</small>";
}
//]]>
</script>
It may be the typo if you incorrectly wrote the placeholder
word.
In my case I misspelled it as placehoder
and got the error like this:
AttributeError: 'module' object has no attribute 'placehoder'