Programs & Examples On #Floor

A function common to many programming languages that returns the next lowest integer value by rounding the value down if necessary.

Countdown timer in React

_x000D_
_x000D_
class Example extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { time: {}, seconds: 5 };_x000D_
    this.timer = 0;_x000D_
    this.startTimer = this.startTimer.bind(this);_x000D_
    this.countDown = this.countDown.bind(this);_x000D_
  }_x000D_
_x000D_
  secondsToTime(secs){_x000D_
    let hours = Math.floor(secs / (60 * 60));_x000D_
_x000D_
    let divisor_for_minutes = secs % (60 * 60);_x000D_
    let minutes = Math.floor(divisor_for_minutes / 60);_x000D_
_x000D_
    let divisor_for_seconds = divisor_for_minutes % 60;_x000D_
    let seconds = Math.ceil(divisor_for_seconds);_x000D_
_x000D_
    let obj = {_x000D_
      "h": hours,_x000D_
      "m": minutes,_x000D_
      "s": seconds_x000D_
    };_x000D_
    return obj;_x000D_
  }_x000D_
_x000D_
  componentDidMount() {_x000D_
    let timeLeftVar = this.secondsToTime(this.state.seconds);_x000D_
    this.setState({ time: timeLeftVar });_x000D_
  }_x000D_
_x000D_
  startTimer() {_x000D_
    if (this.timer == 0 && this.state.seconds > 0) {_x000D_
      this.timer = setInterval(this.countDown, 1000);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  countDown() {_x000D_
    // Remove one second, set state so a re-render happens._x000D_
    let seconds = this.state.seconds - 1;_x000D_
    this.setState({_x000D_
      time: this.secondsToTime(seconds),_x000D_
      seconds: seconds,_x000D_
    });_x000D_
    _x000D_
    // Check if we're at zero._x000D_
    if (seconds == 0) { _x000D_
      clearInterval(this.timer);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return(_x000D_
      <div>_x000D_
        <button onClick={this.startTimer}>Start</button>_x000D_
        m: {this.state.time.m} s: {this.state.time.s}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Example/>, document.getElementById('View'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="View"></div>
_x000D_
_x000D_
_x000D_

How to call a vue.js function on page load

you can also do this using mounted

https://vuejs.org/v2/guide/migration.html#ready-replaced

....
methods:{
    getUnits: function() {...}
},
mounted: function(){
    this.$nextTick(this.getUnits)
}
....

How do I preserve line breaks when getting text from a textarea?

Here is an idea as you may have multiple newline in a textbox:

 var text=document.getElementById('post-text').value.split('\n');
 var html = text.join('<br />');

This HTML value will preserve newline. Hope this helps.

pandas dataframe convert column type to string or categorical

With pandas >= 1.0 there is now a dedicated string datatype:

1) You can convert your column to this pandas string datatype using .astype('string'):

df['zipcode'] = df['zipcode'].astype('string')

2) This is different from using str which sets the pandas object datatype:

df['zipcode'] = df['zipcode'].astype(str)

3) For changing into categorical datatype use:

df['zipcode'] = df['zipcode'].astype('category')

You can see this difference in datatypes when you look at the info of the dataframe:

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
    'zipcode_category': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
 #   Column            Non-Null Count  Dtype   
---  ------            --------------  -----   
 0   zipcode_str       2 non-null      object  
 1   zipcode_string    2 non-null      string  
 2   zipcode_category  2 non-null      category
dtypes: category(1), object(1), string(1)

From the docs:

The 'string' extension type solves several issues with object-dtype NumPy arrays:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than string.

More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html

The response content cannot be parsed because the Internet Explorer engine is not available, or

It is sure because the Invoke-WebRequest command has a dependency on the Internet Explorer assemblies and are invoking it to parse the result as per default behaviour. As Matt suggest, you can simply launch IE and make your selection in the settings prompt which is popping up at first launch. And the error you experience will disappear.

But this is only possible if you run your powershell scripts as the same windows user as whom you launched the IE with. The IE settings are stored under your current windows profile. So if you, like me run your task in a scheduler on a server as the SYSTEM user, this will not work.

So here you will have to change your scripts and add the -UseBasicParsing argument, as ijn this example: $WebResponse = Invoke-WebRequest -Uri $url -TimeoutSec 1800 -ErrorAction:Stop -Method:Post -Headers $headers -UseBasicParsing

Why do we need middleware for async flow in Redux?

To answer the question that is asked in the beginning:

Why can't the container component call the async API, and then dispatch the actions?

Keep in mind that those docs are for Redux, not Redux plus React. Redux stores hooked up to React components can do exactly what you say, but a Plain Jane Redux store with no middleware doesn't accept arguments to dispatch except plain ol' objects.

Without middleware you could of course still do

const store = createStore(reducer);
MyAPI.doThing().then(resp => store.dispatch(...));

But it's a similar case where the asynchrony is wrapped around Redux rather than handled by Redux. So, middleware allows for asynchrony by modifying what can be passed directly to dispatch.


That said, the spirit of your suggestion is, I think, valid. There are certainly other ways you could handle asynchrony in a Redux + React application.

One benefit of using middleware is that you can continue to use action creators as normal without worrying about exactly how they're hooked up. For example, using redux-thunk, the code you wrote would look a lot like

function updateThing() {
  return dispatch => {
    dispatch({
      type: ActionTypes.STARTED_UPDATING
    });
    AsyncApi.getFieldValue()
      .then(result => dispatch({
        type: ActionTypes.UPDATED,
        payload: result
      }));
  }
}

const ConnectedApp = connect(
  (state) => { ...state },
  { update: updateThing }
)(App);

which doesn't look all that different from the original — it's just shuffled a bit — and connect doesn't know that updateThing is (or needs to be) asynchronous.

If you also wanted to support promises, observables, sagas, or crazy custom and highly declarative action creators, then Redux can do it just by changing what you pass to dispatch (aka, what you return from action creators). No mucking with the React components (or connect calls) necessary.

How to add a constant column in a Spark DataFrame?

As the other answers have described, lit and typedLit are how to add constant columns to DataFrames. lit is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.

You'll commonly be using lit to create org.apache.spark.sql.Column objects because that's the column type required by most of the org.apache.spark.sql.functions.

Suppose you have a DataFrame with a some_date DateType column and would like to add a column with the days between December 31, 2020 and some_date.

Here's your DataFrame:

+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+

Here's how to calculate the days till the year end:

val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
  .withColumn("days_till_yearend", diff)
  .show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23|               99|
|2020-01-05|              361|
|2020-04-12|              263|
+----------+-----------------+

You could also use lit to create a year_end column and compute the days_till_yearend like so:

import java.sql.Date

df
  .withColumn("yearend", lit(Date.valueOf("2020-12-31")))
  .withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
  .show()
+----------+----------+-----------------+
| some_date|   yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31|               99|
|2020-01-05|2020-12-31|              361|
|2020-04-12|2020-12-31|              263|
+----------+----------+-----------------+

Most of the time, you don't need to use lit to append a constant column to a DataFrame. You just need to use lit to convert a Scala type to a org.apache.spark.sql.Column object because that's what's required by the function.

See the datediff function signature:

enter image description here

As you can see, datediff requires two Column arguments.

Round number to nearest integer

Use round(x, y). It will round up your number up to your desired decimal place.

For example:

>>> round(32.268907563, 3)
32.269

Getting current unixtimestamp using Moment.js

For anyone who finds this page looking for unix timestamp w/ milliseconds, the documentation says

moment().valueOf()

or

+moment();

you can also get it through moment().format('x') (or .format('X') [capital X] for unix seconds with decimal milliseconds), but that will give you a string. Which moment.js won't actually parse back afterwards, unless you convert/cast it back to a number first.

Mathematical functions in Swift

For the Swift way of doing things, you can try and make use of the tools available in the Swift Standard Library. These should work on any platform that is able to run Swift.

Instead of floor(), round() and the rest of the rounding routines you can use rounded(_:):

let x = 6.5

// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"

// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"

// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"

// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"

These are currently available on Float and Double and it should be easy enough to convert to a CGFloat for example.

Instead of sqrt() there's the squareRoot() method on the FloatingPoint protocol. Again, both Float and Double conform to the FloatingPoint protocol:

let x = 4.0
let y = x.squareRoot()

For the trigonometric functions, the standard library can't help, so you're best off importing Darwin on the Apple platforms or Glibc on Linux. Fingers-crossed they'll be a neater way in the future.

#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif

let x = 1.571
print(sin(x))
// Prints "~1.0"

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

Error: getaddrinfo ENOTFOUND in nodejs for get call

I also had same problem and I fixed it by using right proxy. Please double check your proxy settings if you are using proxy network.

Hope this will help you -

Rounding Bigdecimal values with 2 Decimal Places

I think that the RoundingMode you are looking for is ROUND_HALF_EVEN. From the javadoc:

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.

Here is a quick test case:

BigDecimal a = new BigDecimal("10.12345");
BigDecimal b = new BigDecimal("10.12556");

a = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
b = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);

System.out.println(a);
System.out.println(b);

Correctly prints:

10.12
10.13

UPDATE:

setScale(int, int) has not been recommended since Java 1.5, when enums were first introduced, and was finally deprecated in Java 9. You should now use setScale(int, RoundingMode) e.g:

setScale(2, RoundingMode.HALF_EVEN)

How to Generate a random number of fixed length using JavaScript?

I created the below function to generate random number of fix length:

function getRandomNum(length) {
    var randomNum = 
        (Math.pow(10,length).toString().slice(length-1) + 
        Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length);
    return randomNum;
}

This will basically add 0's at the beginning to make the length of the number as required.

Converting milliseconds to minutes and seconds with Javascript

Event though ,oment.js does not provide such functionality, if you come here and you are already using moment.js, try this:

function formatDuration(ms) {
  var duration = moment.duration(ms);
  return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss");
}

You will get something like x:xx:xx.

In the case you may want to skip the hour, when the duration is only < 60minutes.

function formatDuration(ms) {
  var duration = moment.duration(ms);
  if (duration.asHours() > 1) {
    return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss");
  } else {
    return moment.utc(duration.asMilliseconds()).format("mm:ss");
  }
}

This workaround in moment was introduced in this Issue.

javascript setTimeout() not working

Use:

setTimeout(startTimer,startInterval); 

You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().

Display SQL query results in php

You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.

For getting the result you have to add a lil things in your script like

require_once('db.php');  
 $sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) ORDER BY idM1O LIMIT 1";

 $result = mysql_query($sql);
 //echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    print_r($row);
}

This will give you result;

Stop form refreshing page on submit

In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?

A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.

<form id="prospects_form" method="post">
    <input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
    <input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
    <input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
    <textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>

Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.

"Insert if not exists" statement in SQLite

For a unique column, use this:

INSERT OR REPLACE INTO table () values();

For more information, see: sqlite.org/lang_insert

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

How to break long string to multiple lines

I know that this is super-duper old, but on the off chance that someone comes looking for this, as of Visual Basic 14, Vb supports interpolation. Sooooo cool!

Example:

SQLQueryString = $"
   Insert into Employee values( 
       {txtEmployeeNo}, 
       {txtContractsStartDate},
       {txtSeatNo},
       {txtFloor},
       {txtLeaves}
)"

It works. Documentation Here

Edit: After writing this, I realized that the OP was talking about VBA. This will not work in VBA!!! However, I will leave this up here, because as someone new to VB, I stumbled upon this question looking for a solution to just this problem in VB.net. If this helps someone else, great.

Accessing MVC's model property from Javascript

try this: (you missed the single quotes)

var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';

Get bitcoin historical data

Actually, you CAN get the whole Bitcoin trades history from Bitcoincharts in CSV format here : http://api.bitcoincharts.com/v1/csv/

it is updated twice a day for active exchanges, and there is a few dead exchanges, too.

EDIT: Since there are no column headers in the CSVs, here's what they are : column 1) the trade's timestamp, column 2) the price, column 3) the volume of the trade

browser.msie error after update to jQuery 1.9.1

You can use :

var MSIE = jQuery.support.leadingWhitespace; // This property is not supported by ie 6-8

$(document).ready(function(){

if (MSIE){
    if (navigator.vendor == 'Apple Computer, Inc.'){
        // some code for this navigator
    } else {
       // some code for others browsers
    }

} else {
    // default code

}});

creating a random number using MYSQL

This should give what you want:

FLOOR(RAND() * 401) + 100

Generically, FLOOR(RAND() * (<max> - <min> + 1)) + <min> generates a number between <min> and <max> inclusive.

Update

This full statement should work:

SELECT name, address, FLOOR(RAND() * 401) + 100 AS `random_number` 
FROM users

How to call javascript function on page load in asp.net

Calling JavaScript function on code behind i.e. On Page_Load

ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

If you have UpdatePanel there then try like this

ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

View Blog Article : How to Call javascript function from code behind in asp.net c#

Responsive css background images

This is an easy one =)

body {
    background-image: url(http://domains.com/photo.jpeg);
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
}

Take a look at the jsFiddle demo

Disable automatic sorting on the first column when using jQuery DataTables

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];
}

Disable sorting on last column when using jQuery DataTables

You can use the data attribute data-orderable="false".

<th data-orderable="false">Salary</th>

_x000D_
_x000D_
    $(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_
_x000D_
_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.

Dealing with float precision in Javascript

From this post: How to deal with floating point number precision in JavaScript?

You have a few options:

  • Use a special datatype for decimals, like decimal.js
  • Format your result to some fixed number of significant digits, like this: (Math.floor(y/x) * x).toFixed(2)
  • Convert all your numbers to integers

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

JavaScript adding decimal numbers issue

Testing this Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixed works very well.

What is this Javascript "require"?

Two flavours of module.exports / require:

(see here)

Flavour 1
export file (misc.js):

var x = 5;
var addX = function(value) {
  return value + x;
};
module.exports.x = x;
module.exports.addX = addX;

other file:

var misc = require('./misc');
console.log("Adding %d to 10 gives us %d", misc.x, misc.addX(10));

Flavour 2
export file (user.js):

var User = function(name, email) {
  this.name = name;
  this.email = email;
};
module.exports = User;

other file:

var user = require('./user');
var u = new user();

milliseconds to time in javascript

A possible solution that worked for my case. It turns milliseconds into hh:ss time:

function millisecondstotime(ms) {
var x = new Date(ms);
var y = x.getHours();
if (y < 10) {
y = '0' + y;
} 
var z = x.getMinutes();
if (z < 10) {
    z = '0' + z;
} 
return y + ':' + z;
}

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Generate random password string with requirements in javascript

I have written a small one inspired from your answer:

(function(){g=function(){c='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';p='';for(i=0;i<8;i++){p+=c.charAt(Math.floor(Math.random()*62));}return p;};p=g();while(!/[A-Z]/.test(p)||!/[0-9]/.test(p)||!/[a-z]/.test(p)){p=g();}return p;})()

This function returns the password and can be used in bookmarklet like:

javascript:alert(TheCodeOfTheFunction);

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Undefined reference to `pow' and `floor'

For the benefit of anyone reading this later, you need to link against it as Fred said:

gcc fib.c -lm -o fibo

One good way to find out what library you need to link is by checking the man page if one exists. For example, man pow and man floor will both tell you:

Link with -lm.

An explanation for linking math library in C programming - Linking in C

less than 10 add 0 to number

$('#detect').html( toGeo(apX, screenX)  + latT +', '+ toGeo(apY, screenY) + lonT  );

function toGeo(d, max) {
   var c = '';

   var r = d/max * 180;
   var deg = Math.floor(r);
   if(deg < 10) deg = '0' + deg;
   c += deg + "° ";

   r = (r - deg) * 60;
   var min = Math.floor(r);
   if(min < 10) min = '0' + min;
   c += min + "' ";

   r = (r - min) * 60;
   var sec = Math.floor(r);
   if(sec < 10) sec = '0' + sec;
   c += sec + """;

   return c;
}

Converting a double to an int in Javascript without rounding

Use parseInt().

var num = 2.9
console.log(parseInt(num, 10)); // 2

You can also use |.

var num = 2.9
console.log(num | 0); // 2

How to scroll table's "tbody" independent of "thead"?

mandatory parts:

tbody {
    overflow-y: scroll;  (could be: 'overflow: scroll' for the two axes)
    display: block;
    with: xxx (a number or 100%)
}

thead {
    display: inline-block;
}

Days between two dates?

Do you mean full calendar days, or groups of 24 hours?

For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:

days = (a - b).days

For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:

roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days

Math.random() explanation

int randomWithRange(int min, int max)
{
   int range = (max - min) + 1;     
   return (int)(Math.random() * range) + min;
}

Output of randomWithRange(2, 5) 10 times:

5
2
3
3
2
4
4
4
5
4

The bounds are inclusive, ie [2,5], and min must be less than max in the above example.

EDIT: If someone was going to try and be stupid and reverse min and max, you could change the code to:

int randomWithRange(int min, int max)
{
   int range = Math.abs(max - min) + 1;     
   return (int)(Math.random() * range) + (min <= max ? min : max);
}

EDIT2: For your question about doubles, it's just:

double randomWithRange(double min, double max)
{
   double range = (max - min);     
   return (Math.random() * range) + min;
}

And again if you want to idiot-proof it it's just:

double randomWithRange(double min, double max)
{
   double range = Math.abs(max - min);     
   return (Math.random() * range) + (min <= max ? min : max);
}

Generate random int value from 3 to 6

In general:

select rand()*(@upper-@lower)+@lower;

For your question:

select rand()*(6-3)+3;

<=>

select rand()*3+3;

How to round up integer division and have int result in Java?

Use Math.ceil() and cast the result to int:

  • This is still faster than to avoid doubles by using abs().
  • The result is correct when working with negatives, because -0.999 will be rounded UP to 0

Example:

(int) Math.ceil((double)divident / divisor);

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

Just for fun. The following is a more 'native' Haskell implementation:

import Control.Applicative
import Control.Monad
import Data.Either
import Math.NumberTheory.Powers.Squares

isInt :: RealFrac c => c -> Bool
isInt = (==) <$> id <*> fromInteger . round

intSqrt :: (Integral a) => a -> Int
--intSqrt = fromIntegral . floor . sqrt . fromIntegral
intSqrt = fromIntegral . integerSquareRoot'

factorize :: Int -> [Int]
factorize 1 = []
factorize n = first : factorize (quot n first)
  where first = (!! 0) $ [a | a <- [2..intSqrt n], rem n a == 0] ++ [n]

factorize2 :: Int -> [(Int,Int)]
factorize2 = foldl (\ls@((val,freq):xs) y -> if val == y then (val,freq+1):xs else (y,1):ls) [(0,0)] . factorize

numDivisors :: Int -> Int
numDivisors = foldl (\acc (_,y) -> acc * (y+1)) 1 <$> factorize2

nextTriangleNumber :: (Int,Int) -> (Int,Int)
nextTriangleNumber (n,acc) = (n+1,acc+n+1)

forward :: Int -> (Int, Int) -> Either (Int, Int) (Int, Int)
forward k val@(n,acc) = if numDivisors acc > k then Left val else Right (nextTriangleNumber val)

problem12 :: Int -> (Int, Int)
problem12 n = (!!0) . lefts . scanl (>>=) (forward n (1,1)) . repeat . forward $ n

main = do
  let (n,val) = problem12 1000
  print val

Using ghc -O3, this consistently runs in 0.55-0.58 seconds on my machine (1.73GHz Core i7).

A more efficient factorCount function for the C version:

int factorCount (int n)
{
  int count = 1;
  int candidate,tmpCount;
  while (n % 2 == 0) {
    count++;
    n /= 2;
  }
    for (candidate = 3; candidate < n && candidate * candidate < n; candidate += 2)
    if (n % candidate == 0) {
      tmpCount = 1;
      do {
        tmpCount++;
        n /= candidate;
      } while (n % candidate == 0);
       count*=tmpCount;
      }
  if (n > 1)
    count *= 2;
  return count;
}

Changing longs to ints in main, using gcc -O3 -lm, this consistently runs in 0.31-0.35 seconds.

Both can be made to run even faster if you take advantage of the fact that the nth triangle number = n*(n+1)/2, and n and (n+1) have completely disparate prime factorizations, so the number of factors of each half can be multiplied to find the number of factors of the whole. The following:

int main ()
{
  int triangle = 0,count1,count2 = 1;
  do {
    count1 = count2;
    count2 = ++triangle % 2 == 0 ? factorCount(triangle+1) : factorCount((triangle+1)/2);
  } while (count1*count2 < 1001);
  printf ("%lld\n", ((long long)triangle)*(triangle+1)/2);
}

will reduce the c code run time to 0.17-0.19 seconds, and it can handle much larger searches -- greater than 10000 factors takes about 43 seconds on my machine. I leave a similar haskell speedup to the interested reader.

generate random string for div id

Here is the reusable function to generate the random IDs :

function revisedRandId() {
     return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}

// It will not start with the any number digit so it will be supported by CSS3

Passing route control with optional parameter after root in express?

That would work depending on what client.get does when passed undefined as its first parameter.

Something like this would be safer:

app.get('/:key?', function(req, res, next) {
    var key = req.params.key;
    if (!key) {
        next();
        return;
    }
    client.get(key, function(err, reply) {
        if(client.get(reply)) {
            res.redirect(reply);
        }
        else {
            res.render('index', {
                link: null
            });
        }
    });
});

There's no problem in calling next() inside the callback.

According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

Basic Ajax send/receive with node.js

RESTful API (Route):

rtr.route('/testing')
.get((req, res)=>{
    res.render('test')
})
.post((req, res, next)=>{
       res.render('test')
})

AJAX Code:

$(function(){
$('#anyid').on('click', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'GET',
        contentType: 'application/json',
        success: function(res){
            console.log('GET Request')
        }
    })
})

$('#anyid').on('submit', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            info: "put data here to pass in JSON format."
        }),
        success: function(res){
            console.log('POST Request')
        }
    })
})
})

javascript createElement(), style problem

yourElement.setAttribute("style", "background-color:red; font-size:2em;");

Or you could write the element as pure HTML and use .innerHTML = [raw html code]... that's very ugly though.

In answer to your first question, first you use var myElement = createElement(...);, then you do document.body.appendChild(myElement);.

How can I check if an element exists in the visible DOM?

This code works for me, and I didn't have any issues with it.


    if(document.getElementById("mySPAN")) {
        // If the element exists, execute this code
        alert("Element exists");
    }
    else {
        // If the element does not exist execute this code
        alert("Element does not exists");
    }

Get decimal portion of a number with JavaScript

float a=3.2;
int b=(int)a; // you'll get output b=3 here;
int c=(int)a-b; // you'll get c=.2 value here

HTML Canvas Full Screen

it's simple, set canvas width and height to screen.width and screen.height. then press F11! think F11 should make full screen in most browsers does in FFox and IE.

How to convert seconds to time format?

If the you know the times will be less than an hour, you could just use the date() or $date->format() functions.

$minsandsecs = date('i:s',$numberofsecs);

This works because the system epoch time begins at midnight (on 1 Jan 1970, but that's not important for you).

If it's an hour or more but less than a day, you could output it in hours:mins:secs format with `

$hoursminsandsecs = date('H:i:s',$numberofsecs);

For more than a day, you'll need to use modulus to calculate the number of days, as this is where the start date of the epoch would become relevant.

Hope that helps.

PHP calculate age

If you can't seem to use some of the newer functions, here's something I whipped up. Probably more than you need, and I'm sure there are better ways, but it's easy to read, so it should do the job:

function get_age($date, $units='years')
{
    $modifier = date('n') - date('n', strtotime($date)) ? 1 : (date('j') - date('j', strtotime($date)) ? 1 : 0);
    $seconds = (time()-strtotime($date));
    $years = (date('Y')-date('Y', strtotime($date))-$modifier);
    switch($units)
    {
        case 'seconds':
            return $seconds;
        case 'minutes':
            return round($seconds/60);
        case 'hours':
            return round($seconds/60/60);
        case 'days':
            return round($seconds/60/60/24);
        case 'months':
            return ($years*12+date('n'));
        case 'decades':
            return ($years/10);
        case 'centuries':
            return ($years/100);
        case 'years':
        default:
            return $years;
    }
}

Example Use:

echo 'I am '.get_age('September 19th, 1984', 'days').' days old';

Hope this helps.

Javascript seconds to minutes and seconds

you can use this snippet =>

 const timerCountDown = async () => {
    let date = new Date();
    let time = date.getTime() + 122000;
    let countDownDate = new Date(time).getTime();
    let x = setInterval(async () => {
      let now = new Date().getTime();
      let distance = countDownDate - now;
      let days = Math.floor(distance / (1000 * 60 * 60 * 24));
      let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      let seconds = Math.floor((distance % (1000 * 60)) / 1000);

      if (distance < 1000) {
        // ================== Timer Finished 
        clearInterval(x);
      }
    }, 1000);
  };

What is the behavior of integer division?

Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors

Safest way to convert float to integer in python?

Another code sample to convert a real/float to an integer using variables. "vel" is a real/float number and converted to the next highest INTEGER, "newvel".

import arcpy.math, os, sys, arcpy.da
.
.
with arcpy.da.SearchCursor(densifybkp,[floseg,vel,Length]) as cursor:
 for row in cursor:
    curvel = float(row[1])
    newvel = int(math.ceil(curvel))

Converting byte array to string in javascript

The simplest solution I've found is:

var text = atob(byteArray);

what is this value means 1.845E-07 in excel?

1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.

1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.

C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.

You can specify a format string if you don't want to use the e-notation.

Fast ceiling of an integer division in C / C++

This works for positive or negative numbers:

q = x / y + ((x % y != 0) ? !((x > 0) ^ (y > 0)) : 0);

If there is a remainder, checks to see if x and y are of the same sign and adds 1 accordingly.

How to display all methods of an object?

You can use Object.getOwnPropertyNames() to get all properties that belong to an object, whether enumerable or not. For example:

console.log(Object.getOwnPropertyNames(Math));
//-> ["E", "LN10", "LN2", "LOG2E", "LOG10E", "PI", ...etc ]

You can then use filter() to obtain only the methods:

console.log(Object.getOwnPropertyNames(Math).filter(function (p) {
    return typeof Math[p] === 'function';
}));
//-> ["random", "abs", "acos", "asin", "atan", "ceil", "cos", "exp", ...etc ]

In ES3 browsers (IE 8 and lower), the properties of built-in objects aren't enumerable. Objects like window and document aren't built-in, they're defined by the browser and most likely enumerable by design.

From ECMA-262 Edition 3:

Global Object
There is a unique global object (15.1), which is created before control enters any execution context. Initially the global object has the following properties:

• Built-in objects such as Math, String, Date, parseInt, etc. These have attributes { DontEnum }.
• Additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself.

As control enters execution contexts, and as ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be changed.

I should point out that this means those objects aren't enumerable properties of the Global object. If you look through the rest of the specification document, you will see most of the built-in properties and methods of these objects have the { DontEnum } attribute set on them.


Update: a fellow SO user, CMS, brought an IE bug regarding { DontEnum } to my attention.

Instead of checking the DontEnum attribute, [Microsoft] JScript will skip over any property in any object where there is a same-named property in the object's prototype chain that has the attribute DontEnum.

In short, beware when naming your object properties. If there is a built-in prototype property or method with the same name then IE will skip over it when using a for...in loop.

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

just pass the date time to this func. it would print out in time ago format for you

date_default_timezone_set('your-time-zone');
function convert($datetime){
  $time=strtotime($datetime);
  $diff=time()-$time;
  $diff/=60;
  $var1=floor($diff);
  $var=$var1<=1 ? 'min' : 'mins';
  if($diff>=60){
    $diff/=60;
    $var1=floor($diff);
    $var=$var1<=1 ? 'hr' : 'hrs';
    if($diff>=24){$diff/=24;$var1=floor($diff);$var=$var1<=1 ? 'day' : 'days';
    if($diff>=30.4375){$diff/=30.4375;$var1=floor($diff);$var=$var1<=1 ? 'month' : 'months';
    if($diff>=12){$diff/=12;$var1=floor($diff);$var=$var1<=1 ? 'year' : 'years';}}}}
    echo $var1,' ',$var,' ago';
  }

Changing the interval of SetInterval while it's running

A much simpler way would be to have an if statement in the refreshed function and a control to execute your command at regular time intervals . In the following example, I run an alert every 2 seconds and the interval (intrv) can be changed dynamically...

var i=1;
var intrv=2; // << control this variable

var refreshId = setInterval(function() {
  if(!(i%intrv)) {
    alert('run!');
  }
  i++;
}, 1000);

Random String Generator Returning Same String

For random string generator :

#region CREATE RANDOM STRING WORD
        char[] wrandom = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','S','T','U','V','X','W','Y','Z'};
        Random random = new Random();
        string random_string = "";
        int count = 12; //YOU WILL SPECIFY HOW MANY CHARACTER WILL BE GENERATE
        for (int i = 0; i < count; i++ )
        {
            random_string = random_string + wrandom[random.Next(0, 24)].ToString(); 
        }
        MessageBox.Show(random_string);
        #endregion

Read pdf files with php

Check out FPDF (with FPDI):

http://www.fpdf.org/

http://www.setasign.de/products/pdf-php-solutions/fpdi/

These will let you open an pdf and add content to it in PHP. I'm guessing you can also use their functionality to search through the existing content for the values you need.

Another possible library is TCPDF: https://tcpdf.org/

Update to add a more modern library: PDF Parser

Modelling an elevator using Object-Oriented Analysis and Design

First there is an elevator class. It has a direction (up, down, stand, maintenance), a current floor and a list of floor requests sorted in the direction. It receives request from this elevator.

Then there is a bank. It contains the elevators and receives the requests from the floors. These are scheduled to all active elevators (not in maintenance).

The scheduling will be like:

  • if available pick a standing elevator for this floor.
  • else pick an elevator moving to this floor.
  • else pick a standing elevator on an other floor.
  • else pick the elevator with the lowest load.

Each elevator has a set of states.

  • Maintenance: the elevator does not react to external signals (only to its own signals).
  • Stand: the elevator is fixed on a floor. If it receives a call. And the elevator is on that floor, the doors open. If it is on another floor, it moves in that direction.
  • Up: the elevator moves up. Each time it reaches a floor, it checks if it needs to stop. If so it stops and opens the doors. It waits for a certain amount of time and closes the door (unless someting is moving through them. Then it removes the floor from the request list and checks if there is another request. If so the elevator starts moving again. If not it enters the state stand.
  • Down: like up but in reverse direction.

There are additional signals:

  • alarm. The elevator stops. And if it is on a floor, the doors open, the request list is cleared, the requests moved back to the bank.
  • door open. Opens the doors if an elevator is on a floor and not moving.
  • door closes. Closed the door if they are open.

EDIT: Some elevators don't start at bottom/first_floor esp. in case of skyscrapers.

min_floor & max_floor are two additional attributes for Elevator.

round() for float in C++

As pointed out in comments and other answers, the ISO C++ standard library did not add round() until ISO C++11, when this function was pulled in by reference to the ISO C99 standard math library.

For positive operands in [½, ub] round(x) == floor (x + 0.5), where ub is 223 for float when mapped to IEEE-754 (2008) binary32, and 252 for double when it is mapped to IEEE-754 (2008) binary64. The numbers 23 and 52 correspond to the number of stored mantissa bits in these two floating-point formats. For positive operands in [+0, ½) round(x) == 0, and for positive operands in (ub, +8] round(x) == x. As the function is symmetric about the x-axis, negative arguments x can be handled according to round(-x) == -round(x).

This leads to the compact code below. It compiles into a reasonable number of machine instructions across various platforms. I observed the most compact code on GPUs, where my_roundf() requires about a dozen instructions. Depending on processor architecture and toolchain, this floating-point based approach could be either faster or slower than the integer-based implementation from newlib referenced in a different answer.

I tested my_roundf() exhaustively against the newlib roundf() implementation using Intel compiler version 13, with both /fp:strict and /fp:fast. I also checked that the newlib version matches the roundf() in the mathimf library of the Intel compiler. Exhaustive testing is not possible for double-precision round(), however the code is structurally identical to the single-precision implementation.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>

float my_roundf (float x)
{
    const float half = 0.5f;
    const float one = 2 * half;
    const float lbound = half;
    const float ubound = 1L << 23;
    float a, f, r, s, t;
    s = (x < 0) ? (-one) : one;
    a = x * s;
    t = (a < lbound) ? x : s;
    f = (a < lbound) ? 0 : floorf (a + half);
    r = (a > ubound) ? x : (t * f);
    return r;
}

double my_round (double x)
{
    const double half = 0.5;
    const double one = 2 * half;
    const double lbound = half;
    const double ubound = 1ULL << 52;
    double a, f, r, s, t;
    s = (x < 0) ? (-one) : one;
    a = x * s;
    t = (a < lbound) ? x : s;
    f = (a < lbound) ? 0 : floor (a + half);
    r = (a > ubound) ? x : (t * f);
    return r;
}

uint32_t float_as_uint (float a)
{
    uint32_t r;
    memcpy (&r, &a, sizeof(r));
    return r;
}

float uint_as_float (uint32_t a)
{
    float r;
    memcpy (&r, &a, sizeof(r));
    return r;
}

float newlib_roundf (float x)
{
    uint32_t w;
    int exponent_less_127;

    w = float_as_uint(x);
    /* Extract exponent field. */
    exponent_less_127 = (int)((w & 0x7f800000) >> 23) - 127;
    if (exponent_less_127 < 23) {
        if (exponent_less_127 < 0) {
            /* Extract sign bit. */
            w &= 0x80000000;
            if (exponent_less_127 == -1) {
                /* Result is +1.0 or -1.0. */
                w |= ((uint32_t)127 << 23);
            }
        } else {
            uint32_t exponent_mask = 0x007fffff >> exponent_less_127;
            if ((w & exponent_mask) == 0) {
                /* x has an integral value. */
                return x;
            }
            w += 0x00400000 >> exponent_less_127;
            w &= ~exponent_mask;
        }
    } else {
        if (exponent_less_127 == 128) {
            /* x is NaN or infinite so raise FE_INVALID by adding */
            return x + x;
        } else {
            return x;
        }
    }
    x = uint_as_float (w);
    return x;
}

int main (void)
{
    uint32_t argi, resi, refi;
    float arg, res, ref;

    argi = 0;
    do {
        arg = uint_as_float (argi);
        ref = newlib_roundf (arg);
        res = my_roundf (arg);
        resi = float_as_uint (res);
        refi = float_as_uint (ref);
        if (resi != refi) { // check for identical bit pattern
            printf ("!!!! arg=%08x  res=%08x  ref=%08x\n", argi, resi, refi);
            return EXIT_FAILURE;
        }
        argi++;
    } while (argi);
    return EXIT_SUCCESS;
}

MS SQL Date Only Without Time

FWIW, I've been doing the same thing as you for years

CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam 

Seems to me like this is one of the better ways to strip off time in terms of flexibility, speed and readabily. (sorry). Some UDF functions as suggested can be useful, but UDFs can be slow with larger result sets.

Ball to Ball Collision - Detection and Handling

After some trial and error, I used this document's method for 2D collisions : https://www.vobarian.com/collisions/2dcollisions2.pdf (that OP linked to)

I applied this within a JavaScript program using p5js, and it works perfectly. I had previously attempted to use trigonometrical equations and while they do work for specific collisions, I could not find one that worked for every collision no matter the angle at the which it happened.

The method explained in this document uses no trigonometrical functions whatsoever, it's just plain vector operations, I recommend this to anyone trying to implement ball to ball collision, trigonometrical functions in my experience are hard to generalize. I asked a Physicist at my university to show me how to do it and he told me not to bother with trigonometrical functions and showed me a method that is analogous to the one linked in the document.

NB : My masses are all equal, but this can be generalised to different masses using the equations presented in the document.

Here's my code for calculating the resulting speed vectors after collision :

    //you just need a ball object with a speed and position vector.
    class TBall {
        constructor(x, y, vx, vy) {
            this.r = [x, y];
            this.v = [0, 0];
        }
    }

    //throw two balls into this function and it'll update their speed vectors
    //if they collide, you need to call this in your main loop for every pair of 
    //balls.
    function collision(ball1, ball2) {
        n = [ (ball1.r)[0] - (ball2.r)[0], (ball1.r)[1] - (ball2.r)[1] ];
        un = [n[0] /  vecNorm(n), n[1] / vecNorm(n) ] ;
        ut = [ -un[1], un[0] ];   
        v1n = dotProd(un, (ball1.v));
        v1t = dotProd(ut, (ball1.v) );
        v2n = dotProd(un, (ball2.v) );
        v2t = dotProd(ut, (ball2.v) );
        v1t_p = v1t; v2t_p = v2t;
        v1n_p = v2n; v2n_p = v1n;
        v1n_pvec = [v1n_p * un[0], v1n_p * un[1] ]; 
        v1t_pvec = [v1t_p * ut[0], v1t_p * ut[1] ]; 
        v2n_pvec = [v2n_p * un[0], v2n_p * un[1] ]; 
        v2t_pvec = [v2t_p * ut[0], v2t_p * ut[1] ];
        ball1.v = vecSum(v1n_pvec, v1t_pvec); ball2.v = vecSum(v2n_pvec, v2t_pvec);
    }

How to autosize a textarea using Prototype?

Here is a function I just wrote in jQuery to do it - you can port it to Prototype, but they don't support the "liveness" of jQuery so elements added by Ajax requests will not respond.

This version not only expands, but it also contracts when delete or backspace is pressed.

This version relies on jQuery 1.4.2.

Enjoy ;)

http://pastebin.com/SUKeBtnx

Usage:

$("#sometextarea").textareacontrol();

or (any jQuery selector for example)

$("textarea").textareacontrol();

It was tested on Internet Explorer 7/Internet Explorer 8, Firefox 3.5, and Chrome. All works fine.

Difference between Math.Floor() and Math.Truncate()

Math.floor sliiiide to the left...
Math.ceil sliiiide to the right...
Math.truncate criiiiss crooooss (floor/ceil always towards 0)
Math.round cha cha, real smooth... (go to closest side)

Let's go to work! (¬?_?)

To the left... Math.floor
Take it back now y'all... --
Two hops this time... -=2

Everybody clap your hands ??

How low can you go? Can you go down low? All the way to the floor?

if (this == "wrong")
    return "i don't wanna be right";

Math.truncate(x) is also the same as int(x).
by removing a positive or negative fraction, you're always heading towards 0.

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

How to include jQuery in ASP.Net project?

You can include the script file directly in your page/master page, etc using:

 <script type="text/javascript" src="/scripts/jquery.min.js"></script> 

Us use a Content Delivery network like Google or Microsoft:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 

or:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>     

Test file upload using HTTP PUT method

For curl, how about using the -d switch? Like: curl -X PUT "localhost:8080/urlstuffhere" -d "@filename"?

Using unset vs. setting a variable to empty

As has been said, using unset is different with arrays as well

$ foo=(4 5 6)

$ foo[2]=

$ echo ${#foo[*]}
3

$ unset foo[2]

$ echo ${#foo[*]}
2

subsetting a Python DataFrame

Just for someone looking for a solution more similar to R:

df[(df.Product == p_id) & (df.Time> start_time) & (df.Time < end_time)][['Time','Product']]

No need for data.loc or query, but I do think it is a bit long.

How to create a Custom Dialog box in android?

Simplest way to change the background color and text style is to make custom theme for android alert dialog as below :-

: Just put below code to styles.xml :

    <style name="AlertDialogCustom" parent="@android:style/Theme.Dialog">
    <item name="android:textColor">#999999</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowTitleStyle">@null</item>
    <item name="android:typeface">monospace</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:textSize">@dimen/abc_text_size_medium_material</item>
    <item name="android:background">#80ff00ff</item>
</style>

: Now customization thing is done , now just apply to your alertBuilder object :

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this,R.style.AlertDialogCustom);

Hope , this will help you !

Error - replacement has [x] rows, data has [y]

TL;DR ...and late to the party, but that short explanation might help future googlers..

In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.

A minimal example:

df <- data.frame(a = 1:2); df$a <- 1:3

throws the error

Error in $<-.data.frame(*tmp*, a, value = 1:3) : replacement has 3 rows, data has 2

which is clear, because the vector a of df has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).

Reset C int array to zero : the fastest way?

You can use memset, but only because our selection of types is restricted to integral types.

In general case in C it makes sense to implement a macro

#define ZERO_ANY(T, a, n) do{\
   T *a_ = (a);\
   size_t n_ = (n);\
   for (; n_ > 0; --n_, ++a_)\
     *a_ = (T) { 0 };\
} while (0)

This will give you C++-like functionality that will let you to "reset to zeros" an array of objects of any type without having to resort to hacks like memset. Basically, this is a C analog of C++ function template, except that you have to specify the type argument explicitly.

On top of that you can build a "template" for non-decayed arrays

#define ARRAY_SIZE(a) (sizeof (a) / sizeof *(a))
#define ZERO_ANY_A(T, a) ZERO_ANY(T, (a), ARRAY_SIZE(a))

In your example it would be applied as

int a[100];

ZERO_ANY(int, a, 100);
// or
ZERO_ANY_A(int, a);

It is also worth noting that specifically for objects of scalar types one can implement a type-independent macro

#define ZERO(a, n) do{\
   size_t i_ = 0, n_ = (n);\
   for (; i_ < n_; ++i_)\
     (a)[i_] = 0;\
} while (0)

and

#define ZERO_A(a) ZERO((a), ARRAY_SIZE(a))

turning the above example into

 int a[100];

 ZERO(a, 100);
 // or
 ZERO_A(a);

Unstage a deleted file in git

I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.

To undo the two deleted files I had to unstage all of the files:

git reset HEAD .

At that point I was able to do the checkout of the deleted items:

git checkout -- WorkingFolder/FileName.ext

Finally I was able to restage the rest of the files and continue with my commit.

What exactly does a jar file contain?

JAR stands for Java ARchive. It's a file format based on the popular ZIP file format and is used for aggregating many files into one. Although JAR can be used as a general archiving tool, the primary motivation for its development was so that Java applets and their requisite components (.class files, images and sounds) can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly improves the speed with which an applet can be loaded onto a web page and begin functioning. The JAR format also supports compression, which reduces the size of the file and improves download time still further. Additionally, individual entries in a JAR file may be digitally signed by the applet author to authenticate their origin.

Build not visible in itunes connect

Wow this was super annoying! Honestly I don't know what the problem was because I've uploaded many apps to the appstore via Xcode over the past few years but past couple days I tried like 8 different build uploads over span of 12 hours but NONE of them would show up in iTunesConnect as Processing or anywhere else. I eventually tried Application Loader even though I've NEVER had to use that before. The first try timed out "Fetching Apple Connect token" or something. I CMD+Q and tried Application Loader again and the 2nd time the upload finished ... and now my build shows up in iTunesConnect as processing. OMG that was annoying, confusing and a huge waste of time (typical Apple Dev experience I guess).

Anyhow ... thought I would share my results.

How to set image name in Dockerfile?

Here is another version if you have to reference a specific docker file:

version: "3"
services:
  nginx:
    container_name: nginx
    build:
      context: ../..
      dockerfile: ./docker/nginx/Dockerfile
    image: my_nginx:latest

Then you just run

docker-compose build

Does Enter key trigger a click event?

What personally me fount usable for me is:

(mousedown)="callEvent()" (keyup.enter)="$event.preventDefault()

keyup.enter prevents the event from triggering on keyup, but it still occurs for keydown, that works for me.

nodejs send html file to client

After years, I want to add another approach by using a view engine in Express.js

var fs = require('fs');

app.get('/test', function(req, res, next) {
    var html = fs.readFileSync('./html/test.html', 'utf8')
    res.render('test', { html: html })
    // or res.send(html)
})

Then, do that in your views/test if you choose res.render method at the above code (I'm writing in EJS format):

<%- locals.html %>

That's all.

In this way, you don't need to break your View Engine arrangements.

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

List Git aliases

I use this alias in my global ~/.gitconfig

# ~/.gitconfig

[alias]
    aliases = !git config --get-regexp ^alias\\. | sed -e s/^alias.// -e s/\\ /\\ $(printf \"\\043\")--\\>\\ / | column -t -s $(printf \"\\043\") | sort -k 1

to produce the following output

$ git aliases
aliases   --> !git config --get-regexp ^alias\. | sed -e s/^alias.// -e s/\ /\ $(printf "\043")--\>\ / | column -t -s $(printf "\043") | sort -k 1
ci        --> commit -v
cim       --> commit -m
co        --> checkout
logg      --> log --graph --decorate --oneline
pl        --> pull
st        --> status
...       --> ...

(Note: This works for me in git bash on Windows. For other terminals you may need to adapt the escaping.)


Explanation

  1. !git config --get-regexp ^alias\\. prints all lines from git config that start with alias.
  2. sed -e s/^alias.// removes alias. from the line
  3. sed -e s/\\ /\\ $(printf \"\\043\")--\\>\\ / replaces the first occurrence of a space with \\ $(printf \"\\043\")--\\> (which evaluates to #-->).
  4. column -t -s $(printf \"\\043\") formats all lines into an evenly spaced column table. The character $(printf \"\\043\") which evaluates to # is used as separator.
  5. sort -k 1 sorts all lines based on the value in the first column

$(printf \"\043\")

This just prints the character # (hex 043) which is used for column separation. I use this little hack so the aliases alias itself does not literally contain the # character. Otherwise it would replace those # characters when printing. Note: Change this to another character if you need aliases with literal # signs.

Add a summary row with totals

Try to use union all as below

SELECT [Type], [Total Sales] From Before
union all
SELECT 'Total', Sum([Total Sales]) From Before

if you have problem with ordering, as i-one suggested try this:

select [Type], [Total Sales] 
from (SELECT [Type], [Total Sales], 0 [Key] 
      From Before 
      union all 
      SELECT 'Total', Sum([Total Sales]), 1 From Before) sq 
order by [Key], Type

POST request with a simple string in body with Alamofire

Your example Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) already contains "foo=bar" string as its body. But if you really want string with custom format. You can do this:

Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: [:], encoding: .Custom({
            (convertible, params) in
            var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
            mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
            return (mutableRequest, nil)
        }))

Note: parameters should not be nil

UPDATE (Alamofire 4.0, Swift 3.0):

In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to ParameterEncoding protocol.

extension String: ParameterEncoding {

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try urlRequest.asURLRequest()
        request.httpBody = data(using: .utf8, allowLossyConversion: false)
        return request
    }

}

Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])

How do I convert a number to a numeric, comma-separated formatted string?

Not sure it works in tsql, but some platforms have to_char():

test=#select to_char(131213211653.78, '9,999,999,999,999.99');
        to_char        
-----------------------
    131,213,211,653.78
test=# select to_char(131213211653.78, '9G999G999G999G999D99');
        to_char        
-----------------------
    131,213,211,653.78
test=# select to_char(485, 'RN');
     to_char     
-----------------
         CDLXXXV

As the example suggests, the format's length needs to match that of the number for best results, so you might want to wrap it in a function (e.g. number_format()) if needed.


Converting to money works too, as point out by the other repliers.

test=# select substring(cast(cast(131213211653.78 as money) as varchar) from 2);
     substring      
--------------------
 131,213,211,653.78

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Create a tar.xz in one command

Quick Solution

tarxz() { tar cf - "$1" | xz -4e > "$1".tar.xz ; }
tarxz name_of_directory

(Notice, not name_of_directory/)


Using xz compression options

If you want to use compression options for xz, or if you are using tar on MacOS, you probably want to avoid the tar -cJf syntax.

According to man xz, the way to do this is:

tar cf - filename | xz -4e > filename.tar.xz

Because I liked Wojciech Adam Koszek's format, but not information:

  1. c creates a new archive for the specified files.
  2. f reads from a directory (best to put this second because -cf != -fc)
  3. - outputs to Standard Output
  4. | pipes output to the next command
  5. xz -4e calls xz with the -4e compression option. (equal to -4 --extreme)
  6. > filename.tar.xz directs the tarred and compressed file to filename.tar.xz

where -4e is, use your own compression options. I often use -k to --keep the original file and -9 for really heavy compression. -z to manually set xz to zip, though it defaults to zipping if not otherwise directed.

To uncompress and untar

To echo Rafael van Horn, to uncompress & untar (see note below):

xz -dc filename.tar.xz | tar x

Note: unlike Rafael's answer, use xz -dc instead of catxz. The docs recommend this in case you are using this for scripting. Best to have a habit of using -d or --decompress instead of unxz as well. However, if you must, using those commands from the command line is fine.

Get host domain from URL?

try following statement

 Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
 string pathQuery = myuri.PathAndQuery;
 string hostName = myuri.ToString().Replace(pathQuery , "");

Example1

 Input : http://localhost:4366/Default.aspx?id=notlogin
 Ouput : http://localhost:4366

Example2

 Input : http://support.domain.com/default.aspx?id=12345
 Output: support.domain.com

Showing the same file in both columns of a Sublime Text window

Its Shift + Alt + 2 to split into 2 screens. More options are found under the menu item View -> Layout.
Once the screen is split, you can open files using the shortcuts:
1. Ctrl + P (From existing directories within sublime) or
2. Ctrl + O(Browse directory)

R color scatter plot points based on values

Best thing to do here is to add a column to the data object to represent the point colour. Then update sections of it by filtering.

data<- read.table('sample_data.txtt', header=TRUE, row.name=1)
# Create new column filled with default colour
data$Colour="black"
# Set new column values to appropriate colours
data$Colour[data$col_name2>=3]="red"
data$Colour[data$col_name2<=1]="blue"
# Plot all points at once, using newly generated colours
plot(data$col_name1,data$col_name2, ylim=c(0,5), col=data$Colour, ylim=c(0,10))

It should be clear how to adapt this for plots with more colours & conditions.

Child with max-height: 100% overflows parent

_x000D_
_x000D_
.container {_x000D_
  background: blue;_x000D_
  padding: 10px;_x000D_
  max-height: 200px;_x000D_
  max-width: 200px;_x000D_
  float: left;_x000D_
  margin-right: 20px;_x000D_
}_x000D_
_x000D_
.img1 {_x000D_
  display: block;_x000D_
  max-height: 100%;_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
.img2 {_x000D_
  display: block;_x000D_
  max-height: inherit;_x000D_
  max-width: inherit;_x000D_
}
_x000D_
<!-- example 1  -->_x000D_
<div class="container">_x000D_
  <img class='img1' src="http://via.placeholder.com/350x450" />_x000D_
</div>_x000D_
_x000D_
<!-- example 2  -->_x000D_
_x000D_
<div class="container">_x000D_
  <img class='img2' src="http://via.placeholder.com/350x450" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I played around a little. On a larger image in firefox, I got a good result with using the inherit property value. Will this help you?

.container {
    background: blue;
    padding: 10px;
    max-height: 100px;
    max-width: 100px;
    text-align:center;
}

img {
    max-height: inherit;
    max-width: inherit;
}

Vue.js - How to properly watch for nested data

VueJs deep watch in child objects

new Vue({
    el: "#myElement",
    data: {
        entity: {
            properties: []
        }
    },
    watch: {
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected. Do work...     
            },
            deep: true
        }
    }
});

Why don’t my SVG images scale using the CSS "width" property?

The transform CSS property lets you rotate, scale, skew, or translate an element.

So you can easily use the transform: scale(2.5); option to scale 2.5 times for example.

Is it possible to set a number to NaN or infinity?

Cast from string using float():

>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False

The name 'controlname' does not exist in the current context

I fixed this in my project by backing up the current files (so I still had my code), deleting the current aspx (and child pages), making a new one, and copying the contents of the backup files into the new files.

How to keep keys/values in same order as declared?

Dictionaries will use an order that makes searching efficient, and you cant change that,

You could just use a list of objects (a 2 element tuple in a simple case, or even a class), and append items to the end. You can then use linear search to find items in it.

Alternatively you could create or use a different data structure created with the intention of maintaining order.

NGINX - No input file specified. - php Fast/CGI

I tried all the settings above but this fixed my problem. You have to define nginx to check if the php file actually exists in that location. I found try_files $uri = 404; solving that problem.

location ~ \.php$ {
        try_files  $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock; 
        include fastcgi_params;
        fastcgi_index index.php;
}

How to Load an Assembly to AppDomain with all references recursively?

The Key is the AssemblyResolve event raised by the AppDomain.

[STAThread]
static void Main(string[] args)
{
    fileDialog.ShowDialog();
    string fileName = fileDialog.FileName;
    if (string.IsNullOrEmpty(fileName) == false)
    {
        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        if (Directory.Exists(@"c:\Provisioning\") == false)
            Directory.CreateDirectory(@"c:\Provisioning\");

        assemblyDirectory = Path.GetDirectoryName(fileName);
        Assembly loadedAssembly = Assembly.LoadFile(fileName);

        List<Type> assemblyTypes = loadedAssembly.GetTypes().ToList<Type>();

        foreach (var type in assemblyTypes)
        {
            if (type.IsInterface == false)
            {
                StreamWriter jsonFile = File.CreateText(string.Format(@"c:\Provisioning\{0}.json", type.Name));
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                jsonFile.WriteLine(serializer.Serialize(Activator.CreateInstance(type)));
                jsonFile.Close();
            }
        }
    }
}

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string[] tokens = args.Name.Split(",".ToCharArray());
    System.Diagnostics.Debug.WriteLine("Resolving : " + args.Name);
    return Assembly.LoadFile(Path.Combine(new string[]{assemblyDirectory,tokens[0]+ ".dll"}));
}

alert a variable value

See with the help of the following example if you can use literals and '$' sign in your case.

    function doHomework(subject) {
    
      alert(\`Starting my ${subject} homework.\`);
    
    }

doHomework('maths');

How can INSERT INTO a table 300 times within a loop in SQL?

I would prevent loops in general if i can, set approaches are much more efficient:

INSERT INTO tblFoo
  SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id]) 
  FROM sys.all_objects ORDER BY n;

Demo

Generate a set or sequence without loops

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

The answer was simply moving the PLSQL Developer folder from the "Program Files (x86) into the "Program Files" folder - weird!

What are .iml files in Android Studio?

They are project files, that hold the module information and meta data.

Just add *.iml to .gitignore.

In Android Studio: Press CTRL + F9 to rebuild your project. The missing *.iml files will be generated.

Sending files using POST with HttpURLConnection

based on Mihai's solution, if anyone has the problem of saving images on the server like what happened on my server. change the Bitmap to bytebuffer part to :

ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
        byte[] pixels = bos.toByteArray();

Android - How to regenerate R class?

In order to regenerate the R.class, you will have to try multiple techniques.

  • Remove any R imports from your java source files: import R.android
  • Make sure to open the "Problems" panel by going to Window->Show view->Problems
  • If you do have some errors in your xml resources, you will need to correct those errors. In my case I had to change my id attributes to include the "+" sign as follows: android:id="@+id/grp_txt"
  • Now proceed to do Project->Clean
  • Finally do Project->Close, Project->Open

The "+" sign indicates a new resource id and the forces the aapt tool to create a new resource integer in the R.java class.

phpmyadmin.pma_table_uiprefs doesn't exist

I had similar problems with phpMyAdmin after changing Mysql InnoDB setting to innodb_file_per_table = 1
to move InnoDB tables into separate files.

None of the other answers helped in my case, neither sudo dpkg-reconfigure phpmyadmin nor importing create_tables.sql. Both failed.

What helped was making sure no default-storage-engine, default-tmp-storage-engine and innodb_file_format is enforced in my.cnf

After restarting MySQL and removing+reinstalling phpMyAdmin there are no more errors.

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.

How to use __doPostBack()

I'd just like to add something to this post for asp:button. I've tried clientId and it doesn't seem to work for me:

__doPostBack('<%= btn.ClientID%>', '');

However, getting the UniqueId seems to post back to the server, like below:

__doPostBack('<%= btn.UniqueID%>', '');

This might help someone else in future, hence posting this.

error 1265. Data truncated for column when trying to load data from txt file

I had same problem. I wanted to edit ENUM values in table structure. Problem was because of rows that was saved before and new ENUM values doesn't contain saved values.

Solution was updating old saved rows in MySql table.

How to set full calendar to a specific start date when it's initialized for the 1st time?

If you don't want to load the calendar twice and you don't have a version where defaultDate is implemented, do the following:

Change the following method:

function Calendar(element, options, eventSources) { ... var date = new Date(); ... }

to:

function Calendar(element, options, eventSources) { ... var date = options.defaultDate ? options.defaultDate : new Date(); ... }

Oracle error : ORA-00905: Missing keyword

First, I thought:

"...In Microsoft SQL Server the SELECT...INTO automatically creates the new table whereas Oracle seems to require you to manually create it before executing the SELECT...INTO statement..."

But after manually generating a table, it still did not work, still showing the "missing keyword" error.

So I gave up this time and solved it by first manually creating the table, then using the "classic" SELECT statement:

INSERT INTO assignment_20081120 SELECT * FROM assignment;

Which worked as expected. If anyone come up with an explanaition on how to use the SELECT...INTO in a correct way, I would be happy!

How do I rename the extension for a bunch of files?

You want to use rename :

rename -S .html .txt *.html

This does exactly what you want - it will change the extension from .html to .txt for all files matching *.html.

Note: Greg Hewgill correctly points out this is not a bash builtin; and is a seperate Linux command. If you just need something on Linux this should work fine; if you need something more cross-platform then take a look at one of the other answers.

Binding ComboBox SelectedItem using MVVM

I had a similar problem where the SelectedItem-binding did not update when I selected something in the combobox. My problem was that I had to set UpdateSourceTrigger=PropertyChanged for the binding.

<ComboBox ItemsSource="{Binding SalesPeriods}" 
          SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />

How to get pandas.DataFrame columns containing specific dtype

Someone will give you a better answe than this possibly, but one thing I tend to do is if all my numeric data are int64 or float64 objects, then you can create a dict of the column data types and then use the values to create your list of columns.

So for example, in a dataframe where I have columns of type float64, int64 and object firstly you can look at the data types as so:

DF.dtypes

and if they conform to the standard whereby the non-numeric columns of data are all object types (as they are in my dataframes), then you can do the following to get a list of the numeric columns:

[key for key in dict(DF.dtypes) if dict(DF.dtypes)[key] in ['float64', 'int64']]

Its just a simple list comprehension. Nothing fancy. Again, though whether this works for you will depend upon how you set up you dataframe...

How to check for empty value in Javascript?

Your script seems incorrect in several places.

Try this

var timetemp = document.getElementsByTagName('input');

for (var i = 0; i < timetemp.length; i++){
    if (timetemp[i].value == ""){
        alert ('No value');
    }
    else{
        alert (timetemp[i].value);
    }
}

Example: http://jsfiddle.net/jasongennaro/FSzT2/

Here's what I changed:

  1. started by getting all the inputs via TagName. This makes an array
  2. initialized i with a var and then looped through the timetemp array using the timetemp.length property.
  3. used timetemp[i] to reference each input in the for statement

Post an object as data using Jquery Ajax

I will leave my original answer in place but the below is how you need to approach it. (Forgive me but it is a long time since I have used regular asp.net / web services with jquery:)

You need to use the following js lib json2 library, you can then use the stringify method to ensure your json is in the correct format for the service.

var data0 = {numberId: "1", companyId : "531"};

var json = JSON2.stringify(data0 ); 

$.ajax({
 type: "POST",
 url: "TelephoneNumbers.aspx/DeleteNumber",
 data: json,
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function(msg) {
 alert('In Ajax');
 }
});

UPDATE: Same issue / answer here

How to get current page URL in MVC 3

One thing that isn't mentioned in other answers is case sensitivity, if it is going to be referenced in multiple places (which it isn't in the original question but is worth taking into consideration as this question appears in a lot of similar searches). Based on other answers I found the following worked for me initially:

Request.Url.AbsoluteUri.ToString()

But in order to be more reliable this then became:

Request.Url.AbsoluteUri.ToString().ToLower()

And then for my requirements (checking what domain name the site is being accessed from and showing the relevant content):

Request.Url.AbsoluteUri.ToString().ToLower().Contains("xxxx")

Django request.GET

from django.http import QueryDict

def search(request):
if request.GET.\__contains__("q"):
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'
return HttpResponse(message)

Use this way, django offical document recommended __contains__ method. See https://docs.djangoproject.com/en/1.9/ref/request-response/

How to change MenuItem icon in ActionBar programmatically

Kotlin version:

toolbar.menu.findItem(R.id.notification).icon =
                    ContextCompat.getDrawable(requireContext(), R.drawable.ic_notification)

toolbar.menu.findItem(R.id.notification).isVisible = true

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>

You didnt closed your opening Form in the first place, plus your code is very very messy. I wont go into the "use pdo or mysqli statements, instead of mysql" thats for you to find out on yourself. Also you have a php tag open and close below it, not sure what is needed there. Something else is that your code refers to an external page, which you didnt post, so if something isnt working there, might be handy to post it too.

Please also note that you had spaces between your $row array variables in the form. You have to link those up together by removing the space (see edited section from me). PHP isn't forgiving when it comes to those mistakes.

Then your HTML. I took the liberty to correct that too

<html>
    <head>
        <title> Delegate edit form</title>
    </head>

    <body>
          <p>Delegate update form</p>
<?php
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";

mysql_connect($host,$usernm,$passwd); 
mysql_select_db($database);

$sql = "SELECT * FROM usermaster WHERE User_name='".$Username."'"; // Please look at this too.
$result = mysql_query($sql) or die (mysql_error()); // dont put spaces in between it, else your code wont recognize it the query that needs to be executed
while ($row = mysql_fetch_array($result)){     // here too, you put a space between it
    $Name=$row['Name'];
    $Username=$row['User_name'];
    $Password=$row['User_password'];
    }
?>

Also, try to be specific. "It doesnt work" doesnt help us much, a specific error type is commonly helpful, plus any indication what the code should do (well, it was kinda obvious here, since its a login/register edit here, but for larger chunks of code it should always be explained)

Anyway, welcome to Stack Overflow

How can I change the text color with jQuery?

Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Douglas Crockford, the author of jslint has written (and spoken) about this issue many times. There's a section on this page of his website which covers this:

for Statement

A for class of statements should have the following form:

for (initialization; condition; update) {
    statements
}

for (variable in object) {
    if (filter) {
        statements
    } 
}

The first form should be used with arrays and with loops of a predeterminable number of iterations.

The second form should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object:

for (variable in object) {
    if (object.hasOwnProperty(variable)) {
        statements
    } 
}

Crockford also has a video series on YUI theater where he talks about this. Crockford's series of videos/talks about javascript are a must see if you're even slightly serious about javascript.

Truncate all tables in a MySQL database in one command?

mysqldump -u root -p --no-data dbname > schema.sql
mysqldump -u root -p drop dbname
mysqldump -u root -p < schema.sql

Multiple aggregate functions in HAVING clause

Here I am writing full query which will clear your all doubts

SELECT BillingDate,
       COUNT(*) AS BillingQty,
       SUM(BillingTotal) AS BillingSum
FROM Billings
WHERE BillingDate BETWEEN '2002-05-01' AND '2002-05-31'
GROUP BY BillingDate
HAVING COUNT(*) > 1
AND SUM(BillingTotal) > 100
ORDER BY BillingDate DESC

How to check if a socket is connected/disconnected in C#?

public static class SocketExtensions
{
    private const int BytesPerLong = 4; // 32 / 8
    private const int BitsPerByte = 8;

    public static bool IsConnected(this Socket socket)
    {
        try
        {
            return !(socket.Poll(1000, SelectMode.SelectRead) && socket.Available == 0);
        }
        catch (SocketException)
        {
            return false;
        }
    }


    /// <summary>
    /// Sets the keep-alive interval for the socket.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="time">Time between two keep alive "pings".</param>
    /// <param name="interval">Time between two keep alive "pings" when first one fails.</param>
    /// <returns>If the keep alive infos were succefully modified.</returns>
    public static bool SetKeepAlive(this Socket socket, ulong time, ulong interval)
    {
        try
        {
            // Array to hold input values.
            var input = new[]
            {
                (time == 0 || interval == 0) ? 0UL : 1UL, // on or off
                time,
                interval
            };

            // Pack input into byte struct.
            byte[] inValue = new byte[3 * BytesPerLong];
            for (int i = 0; i < input.Length; i++)
            {
                inValue[i * BytesPerLong + 3] = (byte)(input[i] >> ((BytesPerLong - 1) * BitsPerByte) & 0xff);
                inValue[i * BytesPerLong + 2] = (byte)(input[i] >> ((BytesPerLong - 2) * BitsPerByte) & 0xff);
                inValue[i * BytesPerLong + 1] = (byte)(input[i] >> ((BytesPerLong - 3) * BitsPerByte) & 0xff);
                inValue[i * BytesPerLong + 0] = (byte)(input[i] >> ((BytesPerLong - 4) * BitsPerByte) & 0xff);
            }

            // Create bytestruct for result (bytes pending on server socket).
            byte[] outValue = BitConverter.GetBytes(0);

            // Write SIO_VALS to Socket IOControl.
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            socket.IOControl(IOControlCode.KeepAliveValues, inValue, outValue);
        }
        catch (SocketException)
        {
            return false;
        }

        return true;
    }
}
  1. Copy the SocketExtensions class to your project
  2. Call the SetKeepAlive on your socket - socket.SetKeepAlive(1000, 2);
  3. Add a timer to check the IsConnected function

How can I add a class to a DOM element in JavaScript?

new_row.className = "aClassName";

Here's more information on MDN: className

Parsing a comma-delimited std::string

The C++ String Toolkit Library (Strtk) has the following solution to your problem:

#include <string>
#include <deque>
#include <vector>
#include "strtk.hpp"
int main()
{ 
   std::string int_string = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
   std::vector<int> int_list;
   strtk::parse(int_string,",",int_list);

   std::string double_string = "123.456|789.012|345.678|901.234|567.890";
   std::deque<double> double_list;
   strtk::parse(double_string,"|",double_list);

   return 0;
}

More examples can be found Here

PHP json_encode encoding numbers as strings

Just run into the same problem and was the database returning the values as strings.

I use this as a workaround:

$a = array(
    'id' => $row['id'] * 1,
    'another' => ...,
    'ananother' => ...,
);
$json = json_encode($a);

That is multiplying the value by 1 to cast it into a number

Hope that helps someone

TypeScript and array reduce function

Reduce() is..

  • The reduce() method reduces the array to a single value.
  • The reduce() method executes a provided function for each value of the array (from left-to-right).
  • The return value of the function is stored in an accumulator (result/total).

It was ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

Change to

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

Also you can use in

  1. find max
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. find an element that not repeated.
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6

How to vertically align an image inside a div

You could try setting the CSS of PI to display: table-cell; vertical-align: middle;

phantomjs not waiting for "full" page load

This is an old question, but since I was looking for full page load but for Spookyjs (that uses casperjs and phantomjs) and didn't find my solution, I made my own script for that, with the same approach as the user deemstone . What this approach does is, for a given quantity of time, if the page did not receive or started any request it will end the execution.

On casper.js file (if you installed it globally, the path would be something like /usr/local/lib/node_modules/casperjs/modules/casper.js) add the following lines:

At the top of the file with all the global vars:

var waitResponseInterval = 500
var reqResInterval = null
var reqResFinished = false
var resetTimeout = function() {}

Then inside function "createPage(casper)" just after "var page = require('webpage').create();" add the following code:

 resetTimeout = function() {
     if(reqResInterval)
         clearTimeout(reqResInterval)

     reqResInterval = setTimeout(function(){
         reqResFinished = true
         page.onLoadFinished("success")
     },waitResponseInterval)
 }
 resetTimeout()

Then inside "page.onResourceReceived = function onResourceReceived(resource) {" on the first line add:

 resetTimeout()

Do the same for "page.onResourceRequested = function onResourceRequested(requestData, request) {"

Finally, on "page.onLoadFinished = function onLoadFinished(status) {" on the first line add:

 if(!reqResFinished)
 {
      return
 }
 reqResFinished = false

And that's it, hope this one helps someone in trouble like I was. This solution is for casperjs but works directly for Spooky.

Good luck !

How to put a jpg or png image into a button in HTML

You can use some inline CSS like this

<input type="submit" name="submit" style="background: url(images/stack.png); width:100px; height:25px;" />

Should do the magic, also you may wanna do a border:none; to get rid of the standard borders.

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

I've tried everything here, but for me it was a completely different issue: I had to remove from my *.d.ts any import statements:

import { SomeModuleType } from '3rd-party-module';

After removing the error went away...

Clarification: When we declare a module in a *.d.ts file, it's automatically picked up by the Typescript compiler as an ambient module (the one you don't need to import explicitly). Once we specify the import ... from ..., the file now becomes a normal (ES6) module, and hence won't be picked up automatically. Hence if you still want it to behave as an ambient module, use a different import style like so:

type MyType: import('3rd-party-module').SomeModuleType;

jQuery access input hidden value

You can access hidden fields' values with val(), just like you can do on any other input element:

<input type="hidden" id="foo" name="zyx" value="bar" />

alert($('input#foo').val());
alert($('input[name=zyx]').val());
alert($('input[type=hidden]').val());
alert($(':hidden#foo').val());
alert($('input:hidden[name=zyx]').val());

Those all mean the same thing in this example.

Android Layout Weight

android:Layout_weight can be used when you don't attach a fix value to your width already like fill_parent etc.

Do something like this :

<Button>

Android:layout_width="0dp"
Android:layout_weight=1

-----other parameters
</Button>

Test if string is a number in Ruby on Rails

In rails 4, you need to put require File.expand_path('../../lib', __FILE__) + '/ext/string' in your config/application.rb

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

How does collections.defaultdict work?

Without defaultdict, you can probably assign new values to unseen keys but you cannot modify it. For example:

import collections
d = collections.defaultdict(int)
for i in range(10):
  d[i] += i
print(d)
# Output: defaultdict(<class 'int'>, {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9})

import collections
d = {}
for i in range(10):
  d[i] += i
print(d)
# Output: Traceback (most recent call last): File "python", line 4, in <module> KeyError: 0

AFNetworking Post Request

It's first worth adding (as this answer is still popular 6 years after I initially wrote it...) that the first thing you should consider is whether you should even use AFNetworking. NSURLSession was added in iOS 7 and means you don't need to use AFNetworking in many cases - and one less third party library is always a good thing.

For AFNetworking 3.0:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
                         @"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

For AFNetworking 2.0 (and also using the new NSDictionary syntax):

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"user[height]": height,
                         @"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

If you are stuck using AFNetworking 1.0, you need to do it this way:

NSURL *url = [NSURL URLWithString:@"https://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        height, @"user[height]",
                        weight, @"user[weight]",
                        nil];
[httpClient postPath:@"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"Request Successful, response '%@'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

Calculate age given the birth date in the format YYYYMMDD

Alternate solution, because why not:

function calculateAgeInYears (date) {
    var now = new Date();
    var current_year = now.getFullYear();
    var year_diff = current_year - date.getFullYear();
    var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
    var has_had_birthday_this_year = (now >= birthday_this_year);

    return has_had_birthday_this_year
        ? year_diff
        : year_diff - 1;
}

asp.net: How can I remove an item from a dropdownlist?

Try this code.

If you can add any item and set value in dropdown then try it.

 dropdown1.Items.Insert(0, new ListItem("---All---", "0"));

You can Removed Item in dropdown then try it.

 ListItem removeItem = dropdown1.Items.FindByText("--Please Select--");
 dropdown1.Items.Remove(removeItem);

UIGestureRecognizer on UIImageView

SWIFT 3 Example

override func viewDidLoad() {

    self.backgroundImageView.addGestureRecognizer(
        UITapGestureRecognizer.init(target: self, action:#selector(didTapImageview(_:)))
    )

    self.backgroundImageView.isUserInteractionEnabled = true
}

func didTapImageview(_ sender: Any) {
    // do something
}

No gesture recongnizer delegates or other implementations where necessary.

What is the difference between '@' and '=' in directive scope in AngularJS?

If you would like to see more how this work with a live example. http://jsfiddle.net/juanmendez/k6chmnch/

var app = angular.module('app', []);
app.controller("myController", function ($scope) {
    $scope.title = "binding";
});
app.directive("jmFind", function () {
    return {
        replace: true,
        restrict: 'C',
        transclude: true,
        scope: {
            title1: "=",
            title2: "@"
        },
        template: "<div><p>{{title1}} {{title2}}</p></div>"
    };
});

How to get first record in each group using Linq

var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());

Get Selected Item Using Checkbox in Listview

You can use model class and use setTag() getTag() methods to keep track which items from listview are checked and which not.

More reference for this : listview with checkbox in android

Source code for model

public class Model {

    private boolean isSelected;
    private String animal;

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public boolean getSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}

put this in your custom adapter

 holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();

                if(modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

whole code for customAdapter is

public class CustomAdapter  extends BaseAdapter {

    private Context context;
    public static ArrayList<Model> modelArrayList;


    public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {

        this.context = context;
        this.modelArrayList = modelArrayList;

    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }
    @Override
    public int getItemViewType(int position) {

        return position;
    }

    @Override
    public int getCount() {
        return modelArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return modelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_item, null, true);

            holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
            holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);

            convertView.setTag(holder);
        }else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }


        holder.checkBox.setText("Checkbox "+position);
        holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());

        holder.checkBox.setChecked(modelArrayList.get(position).getSelected());

        holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();

                if(modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

        return convertView;
    }

    private class ViewHolder {

        protected CheckBox checkBox;
        private TextView tvAnimal;

    }

}

How to deserialize a JObject to .NET object

According to this post, it's much better now:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

Documentation: Convert JSON to a Type

React Checkbox not sending onChange

To get the checked state of your checkbox the path would be:

this.refs.complete.state.checked

The alternative is to get it from the event passed into the handleChange method:

event.target.checked

estimating of testing effort as a percentage of development time

Are you talking about automated unit/integration tests or manual tests?

For the former, my rule of thumb (based on measurements) is 40-50% added to development time i.e. if developing a use case takes 10 days (before an QA and serious bugfixing happens), writing good tests takes another 4 to 5 days - though this should best happen before and during development, not afterwards.

Import CSV file as a pandas DataFrame

import pandas as pd
dataset = pd.read_csv('/home/nspython/Downloads/movie_metadata1.csv')

Java: Calculating the angle between two points in degrees

you could add the following:

public float getAngle(Point target) {
    float angle = (float) Math.toDegrees(Math.atan2(target.y - y, target.x - x));

    if(angle < 0){
        angle += 360;
    }

    return angle;
}

by the way, why do you want to not use a double here?

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

I got it to work by Enabling 32 bit applications in the Application Pool advanced settings. Right click on the application pool and choose advanced settings - enable 32 bit applications. This may help someone out there.

Best way to make WPF ListView/GridView sort on column-header clicking?

Try this:

using System.ComponentModel;
youtItemsControl.Items.SortDescriptions.Add(new SortDescription("yourFavoritePropertyFromItem",ListSortDirection.Ascending);

javascript, is there an isObject function like isArray?

You can use typeof operator.

if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
    alert("A is object");
}

Note that because typeof new Number(1) === 'object' while typeof Number(1) === 'number'; the first syntax should be avoided.

Remove NaN from pandas series

If you have a pandas serie with NaN, and want to remove it (without loosing index):

serie = serie.dropna()

# create data for example
data = np.array(['g', 'e', 'e', 'k', 's']) 
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)

0      g
1    NaN
2    NaN
3      k
4      s
dtype: object

# the code
ser = ser.dropna()
print(ser)

0    g
3    k
4    s
dtype: object

how to break the _.each function in underscore.js

Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.

PHP function to get the subdomain of a URL

For those who get 'Error: Strict Standards: Only variables should be passed by reference.' Use like this:

$env = (explode(".",$_SERVER['HTTP_HOST'])); $env = array_shift($env);

How do I get the backtrace for all the threads in GDB?

Is there a command that does?

thread apply all where

Do while loop in SQL Server 2008

You can also use an exit variable if you want your code to be a bit more readable:

DECLARE @Flag int = 0
DECLARE @Done bit = 0

WHILE @Done = 0 BEGIN
    SET @Flag = @Flag + 1
    PRINT @Flag
    IF @Flag >= 5 SET @Done = 1
END

This would probably be more relevant when you have a more complicated loop and are trying to keep track of the logic. As stated loops are expensive so try and use other methods if you can.

angular 2 ngIf and CSS transition/animation

CSS only solution for modern browsers

@keyframes slidein {
    0%   {margin-left:1500px;}
    100% {margin-left:0px;}
}
.note {
    animation-name: slidein;
    animation-duration: .9s;
    display: block;
}

How to download files using axios

This Worked for me. i implemented this solution in reactJS

const requestOptions = {`enter code here`
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};

fetch(`${url}`, requestOptions)
.then((res) => {
    return res.blob();
})
.then((blob) => {
    const href = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = href;
    link.setAttribute('download', 'config.json'); //or any other extension
    document.body.appendChild(link);
    link.click();
})
.catch((err) => {
    return Promise.reject({ Error: 'Something Went Wrong', err });
})

What is the difference between Jupyter Notebook and JupyterLab?

This answer shows the python perspective. Jupyter supports various languages besides python.

Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain.

I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks:

  1. In Jupyterlab, you can create ".py" files, ".ipynb" files, open terminal etc. Jupyter Notebook allows ".ipynb" files while providing you the choice to choose "python 2" or "python 3".
  2. Jupyterlab can open multiple ".ipynb" files inside a single browser tab. Whereas, Jupyter Notebook will create new tab to open new ".ipynb" files every time. Hovering between various tabs of browser is tedious, thus Jupyterlab is more helpful here.

I'd recommend using PIP to install Jupyterlab.

If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps:

  1. Go to the file --> Right click --> Open With --> Choose another app --> More Apps --> Look for another apps on this PC --> Click.
  2. This will open a file explorer window. Now go inside your Python installation folder. You should see Scripts folder. Go inside it.
  3. Once you find jupyter-lab.exe, select that and now it will open the .ipynb files by default on your PC.

Creating a blurring overlay view

If adds a dark blur view for tableView, this will beautifully make it:

tableView.backgroundColor = .clear
let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = tableView.bounds
blurEffectView.autoresizingMask = [.flexibleHeight, .flexibleWidth]


// Assigning blurEffectView to backgroundView instead of addSubview to tableView makes tableView cell not blocked by blurEffectView 
tableView.backgroundView = blurEffectView

GitHub "fatal: remote origin already exists"

First do a:

git remote rm origin

then

git remote add origin https://github.com/your_user/your_app.git

and voila! Worked for me!

How do I grep for all non-ASCII characters?

The easy way is to define a non-ASCII character... as a character that is not an ASCII character.

LC_ALL=C grep '[^ -~]' file.xml

Add a tab after the ^ if necessary.

Setting LC_COLLATE=C avoids nasty surprises about the meaning of character ranges in many locales. Setting LC_CTYPE=C is necessary to match single-byte characters — otherwise the command would miss invalid byte sequences in the current encoding. Setting LC_ALL=C avoids locale-dependent effects altogether.

Print PHP Call Stack

Strange that noone posted this way:

debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);

This actually prints backtrace without the garbage - just what method was called and where.

Get the index of the object inside an array, matching a condition

One step using Array.reduce() - no jQuery

var items = [{id: 331}, {id: 220}, {id: 872}];

var searchIndexForId = 220;
var index = items.reduce(function(searchIndex, item, index){
  if(item.id === searchIndexForId) { 
    console.log('found!');
    searchIndex = index;
  }
  return searchIndex;
}, null);

will return null if index was not found.

How to pass a parameter to Vue @click event handler

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"

ANTLR: Is there a simple example?

For Antlr 4 the java code generation process is below:-

java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g

Update your jar name in classpath accordingly.

How to display a list using ViewBag

Use as variable to cast the Viewbag data to your desired class in view.

@{

IEnumerable<WebApplication1.Models.Person> personlist = ViewBag.data as
IEnumerable<WebApplication1.Models.Person>;
// You may need to write WebApplication.Models.Person where WebApplication.Models is
  the namespace name where the Person class is defined. It is required so that view 
  can know about the class Person. 
}

In view write this

<td>
    @(personlist.FirstOrDefault().Name)
</td>

Simple way to copy or clone a DataRow?

But to make sure that your new row is accessible in the new table, you need to close the table:

DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);

Disabling Chrome cache for website development

Chrome's Cache killer is by far the best option. Since the store URL to install cache killer is down, you can download the CRX file here:

https://www.crx4chrome.com/extensions/jpfbieopdmepaolggioebjmedmclkbap/

once the extension file is downloaded, open Chrome -> more tools -> extensions, then drag the CRX file from the File Explorer or your Desktop (depending the location where you downloaded the file) into the chrome window to install the extension.

What are the differences between json and simplejson Python modules?

I have to disagree with the other answers: the built in json library (in Python 2.7) is not necessarily slower than simplejson. It also doesn't have this annoying unicode bug.

Here is a simple benchmark:

import json
import simplejson
from timeit import repeat

NUMBER = 100000
REPEAT = 10

def compare_json_and_simplejson(data):
    """Compare json and simplejson - dumps and loads"""
    compare_json_and_simplejson.data = data
    compare_json_and_simplejson.dump = json.dumps(data)
    assert json.dumps(data) == simplejson.dumps(data)
    result = min(repeat("json.dumps(compare_json_and_simplejson.data)", "from __main__ import json, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "      json dumps {} seconds".format(result)
    result = min(repeat("simplejson.dumps(compare_json_and_simplejson.data)", "from __main__ import simplejson, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "simplejson dumps {} seconds".format(result)
    assert json.loads(compare_json_and_simplejson.dump) == data
    result = min(repeat("json.loads(compare_json_and_simplejson.dump)", "from __main__ import json, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "      json loads {} seconds".format(result)
    result = min(repeat("simplejson.loads(compare_json_and_simplejson.dump)", "from __main__ import simplejson, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "simplejson loads {} seconds".format(result)


print "Complex real world data:" 
COMPLEX_DATA = {'status': 1, 'timestamp': 1362323499.23, 'site_code': 'testing123', 'remote_address': '212.179.220.18', 'input_text': u'ny monday for less than \u20aa123', 'locale_value': 'UK', 'eva_version': 'v1.0.3286', 'message': 'Successful Parse', 'muuid1': '11e2-8414-a5e9e0fd-95a6-12313913cc26', 'api_reply': {"api_reply": {"Money": {"Currency": "ILS", "Amount": "123", "Restriction": "Less"}, "ProcessedText": "ny monday for less than \\u20aa123", "Locations": [{"Index": 0, "Derived From": "Default", "Home": "Default", "Departure": {"Date": "2013-03-04"}, "Next": 10}, {"Arrival": {"Date": "2013-03-04", "Calculated": True}, "Index": 10, "All Airports Code": "NYC", "Airports": "EWR,JFK,LGA,PHL", "Name": "New York City, New York, United States (GID=5128581)", "Latitude": 40.71427, "Country": "US", "Type": "City", "Geoid": 5128581, "Longitude": -74.00597}]}}}
compare_json_and_simplejson(COMPLEX_DATA)
print "\nSimple data:"
SIMPLE_DATA = [1, 2, 3, "asasd", {'a':'b'}]
compare_json_and_simplejson(SIMPLE_DATA)

And the results on my system (Python 2.7.4, Linux 64-bit):

Complex real world data:
json dumps 1.56666707993 seconds
simplejson dumps 2.25638604164 seconds
json loads 2.71256899834 seconds
simplejson loads 1.29233884811 seconds

Simple data:
json dumps 0.370109081268 seconds
simplejson dumps 0.574181079865 seconds
json loads 0.422876119614 seconds
simplejson loads 0.270955085754 seconds

For dumping, json is faster than simplejson. For loading, simplejson is faster.

Since I am currently building a web service, dumps() is more important—and using a standard library is always preferred.

Also, cjson was not updated in the past 4 years, so I wouldn't touch it.

Failed Apache2 start, no error log

If we have no entries in log files then we can try to debug apache2 using this command:

$ apache2 -S

or

$ apache2 -e debug

Possible output:

[Fri Apr 05 04:04:59.682880 2019] [core:warn] [pid 11086] AH00111: Config variable ${APACHE_RUN_DIR} is not defined
apache2: Syntax error on line 80 of /etc/apache2/apache2.conf: DefaultRuntimeDir must be a valid directory, absolute or relative to ServerRoot

How to query data out of the box using Spring data JPA by both Sort and Pageable?

There are two ways to achieve this:

final PageRequest page1 = new PageRequest(
  0, 20, Direction.ASC, "lastName", "salary"
);

final PageRequest page2 = new PageRequest(
  0, 20, new Sort(
    new Order(Direction.ASC, "lastName"), 
    new Order(Direction.DESC, "salary")
  )
);

dao.findAll(page1);

As you can see the second form is more flexible as it allows to define different direction for every property (lastName ASC, salary DESC).

How can I bind a background color in WPF/XAML?

Important:

Make sure you're using System.Windows.Media.Brush and not System.Drawing.Brush

They're not compatible and you'll get binding errors.

The color enumeration you need to use is also different

System.Windows.Media.Colors.Aquamarine (class name is Colors) <--- use this one System.Drawing.Color.Aquamarine (class name is Color)

If in doubt use Snoop and inspect the element's background property to look for binding errors - or just look in your debug log.

How organize uploaded media in WP?

Currently, media organisation is possible.

The "problem" with the media library in wordpress is always interesting. Check the following plugin to solve this: WordPress Real Media Library. WP RML creates a virtual folder structure based on an own taxonomy.

Drag & Drop your files

It allows you to organize your wordpress media library in a nice way with folders. It is easy to use, just drag&drop your files and move it to a specific folder. Filter when inserting media or create a gallery from a folder.

Turn your WordPress media library to the next level with folders / categories. Get organized with thousands of images.

RML (Real Media Library) is one of the most wanted media wordpress plugins. It is easy to use and it allows you to organize your thousands of images in folders. It is similar to wordpress categories like in the posts.

Use your mouse (or touch) to drag and drop your files. Create, rename, delete or reorder your folders If you want to select a image from the “Select a image”-dialog (e. g. featured image) you can filter when inserting media. Just install this plugin and it works fine with all your image and media files. It also supports multisite.

If you buy, you get: Forever FREE updates and high quality and fast support.

From the product description i can quote. If you want to try the plugin, there is also a demo on the plugin page.

Update #1 (2017-01-27): Manage your uploads physically

A long time ago I started to open this thread and now there is a usable extension plugin for Real Media Library which allows you to physically manage your uploads folder.

enter image description here

Check out this plugin: https://wordpress.org/plugins/physical-custom-upload-folder/

Do you know the wp-content/uploads folder? There, the files are stored in year/month based folders. This can be a very complicated and mass process, especially when you are working with a FTP client like FileZilla.

Moving already uploaded files: This plugin does not allow to move the files physically when you move a file in the Real Media Library because WordPress uses the URL's in different places. It is very hard to maintain such a process. So this only works for new uploads.

Physical organisation on server?

(Please read on if you are developer) I as developer thought about a solution about this. Does it make sense to organize the uploads on server, too? Yes, i think. Many people ask to organize it physically. I think also that the process of moving files on server and updating the image references is very hard to develop. There are many plugins out now, which are saving the URLs in their own-created database-tables.

Please check this thread where i explained the problem: https://wordpress.stackexchange.com/questions/226675/physical-organization-of-wordpress-media-library-real-media-library-plugin

NameError: global name is not defined

That's How Python works. Try this :

from sqlitedbx import SqliteDBzz

Such that you can directly use the name without the enclosing module.Or just import the module and prepend 'sqlitedbx.' to your function,class etc

How to re-index all subarray elements of a multidimensional array?

To reset the keys of all arrays in an array:

$arr = array_map('array_values', $arr);

In case you just want to reset first-level array keys, use array_values() without array_map.

Matplotlib figure facecolor (background color)

If you want to change background color, try this:

plt.rcParams['figure.facecolor'] = 'white'

How to concatenate a std::string and an int?

In alphabetical order:

std::string name = "John";
int age = 21;
std::string result;

// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);

// 2. with C++11
result = name + std::to_string(age);

// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);

// 4. with FastFormat.Write
fastformat::write(result, name, age);

// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);

// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();

// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);

// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);

// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);

// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
  1. is safe, but slow; requires Boost (header-only); most/all platforms
  2. is safe, requires C++11 (to_string() is already included in #include <string>)
  3. is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
  4. (ditto)
  5. is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms
  6. safe, slow, and verbose; requires #include <sstream> (from standard C++)
  7. is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms
  8. is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms
  9. is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms
  10. safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only
  11. is safe, but slow; requires Poco C++ ; most/all platforms

Merge / convert multiple PDF files into one PDF

Considering that pdfunite is part of poppler it has a higher chance to be installed, usage is also simpler than pdftk:

pdfunite in-1.pdf in-2.pdf in-n.pdf out.pdf

What is the connection string for localdb for version 11

This is a fairly old thread, but since I was reinstalling my Visual Studio 2015 Community today, I thought I might add some info on what to use on VS2015, or what might work in general.

To see which instances were installed by default, type sqllocaldb info inside a command prompt. On my machine, I get two instances, the first one named MSSQLLocalDB.

C:\>sqllocaldb info
MSSQLLocalDB
ProjectsV13

You can also create a new instance if you wish, using sqllocaldb create "some_instance_name", but the default one will work just fine:

// if not using a verbatim string literal, don't forget to escape backslashes
@"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;"

Field 'id' doesn't have a default value?

Solution: Remove STRICT_TRANS_TABLES from sql_mode

To check your default setting,

mysql> set @@sql_mode = 
'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
Query OK, 0 rows affected (0.00 sec)

mysql> select @@sql_mode;
+----------------------------------------------------------------+
| @@sql_mode                                                     |
+----------------------------------------------------------------+
| STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------------------------+
1 row in set (0.00 sec)

Run a sample query

mysql> INSERT INTO nb (id) VALUES(3);
ERROR 1364 (HY000): Field 'field' doesn't have a default value

Remove your STRICT_TRANS_TABLES by resetting it to null.

mysql> set @@sql_mode = '';
Query OK, 0 rows affected (0.00 sec)

Now, run the same test query.

mysql> INSERT INTO nb (id) VALUES(3);
Query OK, 1 row affected, 1 warning (0.00 sec)

Source: https://netbeans.org/bugzilla/show_bug.cgi?id=190731

How to delete all rows from all tables in a SQL Server database?

You could delete all the rows from all tables using an approach like Rubens suggested, or you could just drop and recreate all the tables. Always a good idea to have the full db creation scripts anyway so that may be the easiest/quickest method.

How to create an installer for a .net Windows Service using Visual Studio

InstallUtil classes ( ServiceInstaller ) are considered an anti-pattern by the Windows Installer community. It's a fragile, out of process, reinventing of the wheel that ignores the fact that Windows Installer has built-in support for Services.

Visual Studio deployment projects ( also not highly regarded and deprecated in the next release of Visual Studio ) do not have native support for services. But they can consume merge modules. So I would take a look at this blog article to understand how to create a merge module using Windows Installer XML that can express the service and then consume that merge module in your VDPROJ solution.

Augmenting InstallShield using Windows Installer XML - Windows Services

IsWiX Windows Service Tutorial

IsWiX Windows Service Video

Spring MVC UTF-8 Encoding

To solve this issue you need below three steps:

  1. Set page encoding to UTF-8 like below:

    <%@ page language="java" pageEncoding="UTF-8"%>
    <%@ page contentType="text/html;charset=UTF-8" %>
    
  2. Set filter in web.xml file as below:

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
  3. Set resource encoding to UTF-8, in case if you are writing any UTF-8 characters in Java code or JSP directly.

what is <meta charset="utf-8">?

That meta tag basically specifies which character set a website is written with.

Here is a definition of UTF-8:

UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.

Getting started with Haskell

I'm going to order this guide by the level of skill you have in Haskell, going from an absolute beginner right up to an expert. Note that this process will take many months (years?), so it is rather long.

Absolute Beginner

Firstly, Haskell is capable of anything, with enough skill. It is very fast (behind only C and C++ in my experience), and can be used for anything from simulations to servers, guis and web applications.

However there are some problems that are easier to write for a beginner in Haskell than others. Mathematical problems and list process programs are good candidates for this, as they only require the most basic of Haskell knowledge to be able to write.

Some good guides to learning the very basics of Haskell are the Happy Learn Haskell Tutorial and the first 6 chapters of Learn You a Haskell for Great Good (or its JupyterLab adaptation). While reading these, it is a very good idea to also be solving simple problems with what you know.

Another two good resources are Haskell Programming from first principles, and Programming in Haskell. They both come with exercises for each chapter, so you have small simple problems matching what you learned on the last few pages.

A good list of problems to try is the haskell 99 problems page. These start off very basic, and get more difficult as you go on. It is very good practice doing a lot of those, as they let you practice your skills in recursion and higher order functions. I would recommend skipping any problems that require randomness as that is a bit more difficult in Haskell. Check this SO question in case you want to test your solutions with QuickCheck (see Intermediate below).

Once you have done a few of those, you could move on to doing a few of the Project Euler problems. These are sorted by how many people have completed them, which is a fairly good indication of difficulty. These test your logic and Haskell more than the previous problems, but you should still be able to do the first few. A big advantage Haskell has with these problems is Integers aren't limited in size. To complete some of these problems, it will be useful to have read chapters 7 and 8 of learn you a Haskell as well.

Beginner

After that you should have a fairly good handle on recursion and higher order functions, so it would be a good time to start doing some more real world problems. A very good place to start is Real World Haskell (online book, you can also purchase a hard copy). I found the first few chapters introduced too much too quickly for someone who has never done functional programming/used recursion before. However with the practice you would have had from doing the previous problems you should find it perfectly understandable.

Working through the problems in the book is a great way of learning how to manage abstractions and building reusable components in Haskell. This is vital for people used to object-orientated (oo) programming, as the normal oo abstraction methods (oo classes) don't appear in Haskell (Haskell has type classes, but they are very different to oo classes, more like oo interfaces). I don't think it is a good idea to skip chapters, as each introduces a lot new ideas that are used in later chapters.

After a while you will get to chapter 14, the dreaded monads chapter (dum dum dummmm). Almost everyone who learns Haskell has trouble understanding monads, due to how abstract the concept is. I can't think of any concept in another language that is as abstract as monads are in functional programming. Monads allows many ideas (such as IO operations, computations that might fail, parsing,...) to be unified under one idea. So don't feel discouraged if after reading the monads chapter you don't really understand them. I found it useful to read many different explanations of monads; each one gives a new perspective on the problem. Here is a very good list of monad tutorials. I highly recommend the All About Monads, but the others are also good.

Also, it takes a while for the concepts to truly sink in. This comes through use, but also through time. I find that sometimes sleeping on a problem helps more than anything else! Eventually, the idea will click, and you will wonder why you struggled to understand a concept that in reality is incredibly simple. It is awesome when this happens, and when it does, you might find Haskell to be your favorite imperative programming language :)

To make sure that you are understanding Haskell type system perfectly, you should try to solve 20 intermediate haskell exercises. Those exercises using fun names of functions like "furry" and "banana" and helps you to have a good understanding of some basic functional programming concepts if you don't have them already. Nice way to spend your evening with a bunch of papers covered with arrows, unicorns, sausages and furry bananas.

Intermediate

Once you understand Monads, I think you have made the transition from a beginner Haskell programmer to an intermediate haskeller. So where to go from here? The first thing I would recommend (if you haven't already learnt them from learning monads) is the various types of monads, such as Reader, Writer and State. Again, Real world Haskell and All about monads gives great coverage of this. To complete your monad training learning about monad transformers is a must. These let you combine different types of Monads (such as a Reader and State monad) into one. This may seem useless to begin with, but after using them for a while you will wonder how you lived without them.

Now you can finish the real world Haskell book if you want. Skipping chapters now doesn't really matter, as long as you have monads down pat. Just choose what you are interested in.

With the knowledge you would have now, you should be able to use most of the packages on cabal (well the documented ones at least...), as well as most of the libraries that come with Haskell. A list of interesting libraries to try would be:

  • Parsec: for parsing programs and text. Much better than using regexps. Excellent documentation, also has a real world Haskell chapter.

  • QuickCheck: A very cool testing program. What you do is write a predicate that should always be true (eg length (reverse lst) == length lst). You then pass the predicate the QuickCheck, and it will generate a lot of random values (in this case lists) and test that the predicate is true for all results. See also the online manual.

  • HUnit: Unit testing in Haskell.

  • gtk2hs: The most popular gui framework for Haskell, lets you write gtk applications.

  • happstack: A web development framework for Haskell. Doesn't use databases, instead a data type store. Pretty good docs (other popular frameworks would be snap and yesod).

Also, there are many concepts (like the Monad concept) that you should eventually learn. This will be easier than learning Monads the first time, as your brain will be used to dealing with the level of abstraction involved. A very good overview for learning about these high level concepts and how they fit together is the Typeclassopedia.

  • Applicative: An interface like Monads, but less powerful. Every Monad is Applicative, but not vice versa. This is useful as there are some types that are Applicative but are not Monads. Also, code written using the Applicative functions is often more composable than writing the equivalent code using the Monad functions. See Functors, Applicative Functors and Monoids from the learn you a haskell guide.

  • Foldable,Traversable: Typeclasses that abstract many of the operations of lists, so that the same functions can be applied to other container types. See also the haskell wiki explanation.

  • Monoid: A Monoid is a type that has a zero (or mempty) value, and an operation, notated <> that joins two Monoids together, such that x <> mempty = mempty <> x = x and x <> (y <> z) = (x <> y) <> z. These are called identity and associativity laws. Many types are Monoids, such as numbers, with mempty = 0 and <> = +. This is useful in many situations.

  • Arrows: Arrows are a way of representing computations that take an input and return an output. A function is the most basic type of arrow, but there are many other types. The library also has many very useful functions for manipulating arrows - they are very useful even if only used with plain old Haskell functions.

  • Arrays: the various mutable/immutable arrays in Haskell.

  • ST Monad: lets you write code with a mutable state that runs very quickly, while still remaining pure outside the monad. See the link for more details.

  • FRP: Functional Reactive Programming, a new, experimental way of writing code that handles events, triggers, inputs and outputs (such as a gui). I don't know much about this though. Paul Hudak's talk about yampa is a good start.

There are a lot of new language features you should have a look at. I'll just list them, you can find lots of info about them from google, the haskell wikibook, the haskellwiki.org site and ghc documentation.

  • Multiparameter type classes/functional dependencies
  • Type families
  • Existentially quantified types
  • Phantom types
  • GADTS
  • others...

A lot of Haskell is based around category theory, so you may want to look into that. A good starting point is Category Theory for Computer Scientist. If you don't want to buy the book, the author's related article is also excellent.

Finally you will want to learn more about the various Haskell tools. These include:

  • ghc (and all its features)
  • cabal: the Haskell package system
  • darcs: a distributed version control system written in Haskell, very popular for Haskell programs.
  • haddock: a Haskell automatic documentation generator

While learning all these new libraries and concepts, it is very useful to be writing a moderate-sized project in Haskell. It can be anything (e.g. a small game, data analyser, website, compiler). Working on this will allow you to apply many of the things you are now learning. You stay at this level for ages (this is where I'm at).

Expert

It will take you years to get to this stage (hello from 2009!), but from here I'm guessing you start writing phd papers, new ghc extensions, and coming up with new abstractions.

Getting Help

Finally, while at any stage of learning, there are multiple places for getting information. These are:

  • the #haskell irc channel
  • the mailing lists. These are worth signing up for just to read the discussions that take place - some are very interesting.
  • other places listed on the haskell.org home page

Conclusion

Well this turned out longer than I expected... Anyway, I think it is a very good idea to become proficient in Haskell. It takes a long time, but that is mainly because you are learning a completely new way of thinking by doing so. It is not like learning Ruby after learning Java, but like learning Java after learning C. Also, I am finding that my object-orientated programming skills have improved as a result of learning Haskell, as I am seeing many new ways of abstracting ideas.

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040

How can I post an array of string to ASP.NET MVC Controller without a form?

FYI: JQuery changed the way they serialize post data.

http://forum.jquery.com/topic/nested-param-serialization

You have to set the 'Traditional' setting to true, other wise

{ Values : ["1", "2", "3"] }

will come out as

Values[]=1&Values[]=2&Values[]=3

instead of

Values=1&Values=2&Values=3

minimum double value in C/C++

Try this:

-1 * numeric_limits<double>::max()

Reference: numeric_limits

This class is specialized for each of the fundamental types, with its members returning or set to the different values that define the properties that type has in the specific platform in which it compiles.

Format in kotlin string templates

Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:

"pi = ${pi.format(2)}"

the .format(n) function you'd need to define yourself as

fun Double.format(digits: Int) = "%.${digits}f".format(this)

There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.

How to do URL decoding in Java?

 try {
        String result = URLDecoder.decode(urlString, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

How to sort mongodb with pymongo

Say, you want to sort by 'created_on' field, then you can do like this,

.sort('{}'.format('created_on'), 1 if sort_type == 'asc' else -1)

How do I change the background of a Frame in Tkinter?

You use ttk.Frame, bg option does not work for it. You should create style and apply it to the frame.

from tkinter import *
from tkinter.ttk import * 

root = Tk()

s = Style()
s.configure('My.TFrame', background='red')

mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()

mvn command is not recognized as an internal or external command

Right click on My Computer >> Properties >> Advanced system settings >> System Properties window will get displayed Under Advanced >> Environment Variables

Click on New to set Environment Variables

Variable name: JAVA_HOME Variable value: C:\Program Files\Java\jdk1.8.0_121

Variable name: M2 Variable value: %M2_HOME%\bin

Variable name: M2_HOME Variable value: C:\Program Files\Apache Software Foundation\apache-maven-3.5.0

Variable name: Path Variable value: %M2_HOME%\bin

Then click on Ok, ok, ok. Now restart you command prompt and check again with “mvn –version” to verify the mvn is running, you may restart your system also.

It's Working...... Enjoy :)

Thanks Sandeep Nehte

jquery json to string?

You could parse the JSON to an object, then create your malformed JSON from the ajavscript object. This may not be the best performance-wise, tho.

Otherwise, if you only need to make very small changes to the string, just treat it as a string, and mangle it using standard javascript.

Hive: Filtering Data between Specified Dates when Date is a String

Just like SQL, Hive supports BETWEEN operator for more concise statement:

SELECT *
  FROM your_table
  WHERE your_date_column BETWEEN '2010-09-01' AND '2013-08-31';

How to Set Variables in a Laravel Blade Template

Assign variable to the blade template, Here are the solutions

We can use <?php ?> tag in blade page

<?php $var = 'test'; ?>
{{ $var }

OR

We can use the blade comment with special syntax

{{--*/ $var = 'test' /*--}}
{{ $var }}

Running an Excel macro via Python?

Just a quick note with a xlsm with spaces.

file = 'file with spaces.xlsm'
excel_macro.Application.Run('\'' + file + '\'' + "!Module1.Macro1")

make a header full screen (width) css

html:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"
</head>
<body>
<ul class="menu">
    <li><a href="#">My Dashboard</a>
        <ul>
            <li><a href="#" class="learn">Learn</a></li>
            <li><a href="#" class="teach">Teach</a></li>
            <li><a href="#" class="Mylibrary">My Library</a></li>
        </ul>
    </li>
    <li><a href="#">Likes</a>
        <ul>
            <li><a href="#" class="Pics">Pictures</a></li>
            <li><a href="#" class="audio">Audio</a></li>
            <li><a href="#" class="Videos">Videos</a></li>
        </ul>
</li>
    <li><a href="#">Views</a>
        <ul>
            <li><a href="#" class="documents">Documents</a></li>
            <li><a href="#" class="messages">Messages</a></li>
            <li><a href="#" class="signout">Videos</a></li>
        </ul>
    </li>
        <li><a href="#">account</a>
        <ul>
            <li><a href="#" class="SI">Sign In</a></li>
            <li><a href="#" class="Reg">Register</a></li>
            <li><a href="#" class="Deactivate">Deactivate</a></li>
        </ul>
    </li>
    <li><a href="#">Uploads</a>
        <ul>
            <li><a href="#" class="Pics">Pictures</a></li>
            <li><a href="#" class="audio">Audio</a></li>
            <li><a href="#" class="Videos">Videos</a></li>
        </ul>
    </li>
    <li><a href="#">Videos</a>
    <ul>
            <li><a href="#" class="Add">Add</a></li>
            <li><a href="#" class="delete">Delete</a></li>
    </ul>
    </li>
    <li><a href="#">Documents</a>
    <ul>
            <li><a href="#" class="Add">Upload</a></li>
            <li><a href="#" class="delete">Download</a></li>
    </ul>
    </li>
</ul>
</body>
</html>

css:

.menu,
.menu ul,
.menu li,
.menu a {
    margin: 0;
    padding: 0;
    border: none;
    outline: none;
}
body{
    max-width:110%;
    margin-left:0;
}
.menu {
    height: 40px;
    width:110%;
    margin-left:-4px;
    margin-top:-10px;

    background: #4c4e5a;
    background: -webkit-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -moz-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -o-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: -ms-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
    background: linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);

    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
}
.menu li {
    position: relative;
    list-style: none;
    float: left;
    display: block;
    height: 40px;
}
.menu li a {
    display: block;
    padding: 0 14px;
    margin: 6px 0;
    line-height: 28px;
    text-decoration: none;

    border-left: 1px solid #393942;
    border-right: 1px solid #4f5058;

    font-family: Helvetica, Arial, sans-serif;
    font-weight: bold;
    font-size: 13px;

    color: #f3f3f3;
    text-shadow: 1px 1px 1px rgba(0,0,0,.6);

    -webkit-transition: color .2s ease-in-out;
    -moz-transition: color .2s ease-in-out;
    -o-transition: color .2s ease-in-out;
    -ms-transition: color .2s ease-in-out;
    transition: color .2s ease-in-out;
}

.menu li:first-child a { border-left: none; }
.menu li:last-child a{ border-right: none; }

.menu li:hover > a { color: #8fde62; }
.menu ul {
    position: absolute;
    top: 40px;
    left: 0;

    opacity: 0;
    background: #1f2024;

    -webkit-border-radius: 0 0 5px 5px;
    -moz-border-radius: 0 0 5px 5px;
    border-radius: 0 0 5px 5px;

    -webkit-transition: opacity .25s ease .1s;
    -moz-transition: opacity .25s ease .1s;
    -o-transition: opacity .25s ease .1s;
    -ms-transition: opacity .25s ease .1s;
    transition: opacity .25s ease .1s;
}

.menu li:hover > ul { opacity: 1; }

.menu ul li {
    height: 0;
    overflow: hidden;
    padding: 0;

    -webkit-transition: height .25s ease .1s;
    -moz-transition: height .25s ease .1s;
    -o-transition: height .25s ease .1s;
    -ms-transition: height .25s ease .1s;
    transition: height .25s ease .1s;
}

.menu li:hover > ul li {
    height: 36px;
    overflow: visible;
    padding: 0;
}

.menu ul li a {
    width: 100px;
    padding: 4px 0 4px 40px;
    margin: 0;

    border: none;
    border-bottom: 1px solid #353539;
}

.menu ul li:last-child a { border: none; }

demo here

try also resizing the browser tab to see it in action

How to escape the % (percent) sign in C's printf?

The double '%' works also in ".Format(…). Example (with iDrawApertureMask == 87, fCornerRadMask == 0.05): csCurrentLine.Format("\%ADD%2d%C,%6.4f*\%",iDrawApertureMask,fCornerRadMask) ; gives the desired and expected value of (string contents in) csCurrentLine; "%ADD87C, 0.0500*%"

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

If you're using jquery, you can call this right before your radio buttons.

$('input:radio:first').attr('checked', true);

^ This will check the first radio box, but you can look at more jquery to cycle through to the one you want selected.

How to find a value in an array of objects in JavaScript?

jQuery has a built-in method jQuery.grep that works similarly to the ES5 filter function from @adamse's Answer and should work fine on older browsers.

Using adamse's example:

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

you can do the following

jQuery.grep(peoples, function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

Watermark / hint text / placeholder TextBox

You can keep a seperate value for the entered text and you can set it along with the "Text" field of the text box in the "GotFocus" and "LostFocus" events. When you get the focus, you'll want to clear the text box if there is no value. And when you loss the focus, you'll want to set the get the "Text" value from the text box and then reset the "Text" value of the text box to the place holder if it is empty.

private String username = "";

private void usernameTextBox_GotFocus(object sender, RoutedEventArgs e) {
  if (String.IsNullOrEmpty(username)) {
    usernameTextBox.Text = "";
  }
}

private void usernameTextBox_LostFocus(object sender, RoutedEventArgs e) {
  username = usernameTextBox.Text;
  if (String.IsNullOrEmpty(usernameTextBox.Text)) {
    usernameTextBox.Text = "Username";
  }
}

Then you just have to make sure that the "Text" value of the text box is initialized to the place holder text.

<TextBox x:Name="usernameTextBox" Text="Username" GotFocus="usernameTextBox_GotFocus" LostFocus="usernameTextBox_LostFocus" />

You can further extract this into a class that extends the "TextBox" class and then reuse it through out your project.

namespace UI {
  public class PlaceholderTextBox : TextBox {
    public String Value { get; set; }
    public String PlaceholderText { get; set; }
    public Brush PlaceholderBrush { get; set; }
    private Brush ValuedBrush { get; set; }

    public PlaceholderTextBox() : base() {}

    protected override void OnInitialized(EventArgs e) {
      base.OnInitialized(e);

      ValuedBrush = this.Foreground;

      if (String.IsNullOrEmpty(this.Text)) {
        this.Text = PlaceholderText;
        this.Foreground = PlaceholderBrush;
      }
    }

    protected override void OnGotFocus(System.Windows.RoutedEventArgs e) {
      this.Foreground = ValuedBrush;
      if (String.IsNullOrEmpty(Value)) {
        this.Text = "";
      }

      base.OnGotFocus(e);
    }

    protected override void OnLostFocus(System.Windows.RoutedEventArgs e) {
      Value = this.Text;
      if (String.IsNullOrEmpty(this.Text)) {
        this.Text = PlaceholderText;
        this.Foreground = PlaceholderBrush;
      }

      base.OnLostFocus(e);
    }
  }
}

And then this can be added in the directly in the xaml.

<Window x:Class="UI.LoginWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:m="clr-namespace:UI"
        Initialized="Window_Initialized">
    <Grid>
        <m:PlaceholderTextBox x:Name="usernameTextBox" PlaceholderText="Username" PlaceholderBrush="Gray" />
    </Grid>
</Window>

invalid conversion from 'const char*' to 'char*'

string::c.str() returns a string of type const char * as seen here

A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str());

While the above may work, it is undefined behaviour, and unsafe.

Here's a nicer solution using templates:

char * my_argument = const_cast<char*> ( ...c_str() );

Generate random numbers using C++11 random library

Here's something that I just wrote along those lines::

#include <random>
#include <chrono>
#include <thread>

using namespace std;

//==============================================================
// RANDOM BACKOFF TIME
//==============================================================
class backoff_time_t {
  public:
    random_device                      rd;
    mt19937                            mt;
    uniform_real_distribution<double>  dist;

    backoff_time_t() : rd{}, mt{rd()}, dist{0.5, 1.5} {}

    double rand() {
      return dist(mt);
    }
};

thread_local backoff_time_t backoff_time;


int main(int argc, char** argv) {
   double x1 = backoff_time.rand();
   double x2 = backoff_time.rand();
   double x3 = backoff_time.rand();
   double x4 = backoff_time.rand();
   return 0;
}

~

Apply CSS rules to a nested class inside a div

Use Css Selector for this, or learn more about Css Selector just go here https://www.w3schools.com/cssref/css_selectors.asp

#main_text > .title {
  /* Style goes here */
}

#main_text .title {
  /* Style goes here */
}

Bulk package updates using Conda

the Conda Package Manager is almost ready for beta testing, but it will not be fully integrated until the release of Spyder 2.4 (https://github.com/spyder-ide/spyder/wiki/Roadmap). As soon as we have it ready for testing we will post something on the mailing list (https://groups.google.com/forum/#!forum/spyderlib). Be sure to subscribe

Cheers!

How to pass integer from one Activity to another?

Their are two methods you can use to pass an integer. One is as shown below.

A.class

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

B.class

Intent intent = getIntent();
int intValue = intent.getIntExtra("intVariableName", 0);

The other method converts the integer to a string and uses the following code.

A.class

Intent intent = new Intent(A.this, B.class);
Bundle extras = new Bundle();
extras.putString("StringVariableName", intValue + "");
intent.putExtras(extras);
startActivity(intent);

The code above will pass your integer value as a string to class B. On class B, get the string value and convert again as an integer as shown below.

B.class

   Bundle extras = getIntent().getExtras();
   String stringVariableName = extras.getString("StringVariableName");
   int intVariableName = Integer.parseInt(stringVariableName);

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

When debugging an assembly by starting an external application there are some extra considerations:

  • The external app may load its own copies of assemblies (DLLs) from a manifest file. (e.g., file appname.exe.manifest) If so, you need to disable this possibly by manually altering the manifest.

  • The external app may just try to load from DLLs in its own folder, even without a manifest. You will have to remove / rename these.

With these steps taken care of, the version of the assembly running in the debugger should be correctly loaded and can be debugged normally.

Using jQuery to build table rows from AJAX response(json)

$.ajax({
  type: 'GET',
  url: urlString ,
  dataType: 'json',
  success: function (response) {
    var trHTML = '';
    for(var f=0;f<response.length;f++) {
      trHTML += '<tr><td><strong>' + response[f]['app_action_name']+'</strong></td><td><span class="label label-success">'+response[f]['action_type'] +'</span></td><td>'+response[f]['points']+'</td></tr>';
     }
    $('#result').html(trHTML); 
    $( ".spin-grid" ).removeClass( "fa-spin" );
  }
});

Prevent multiple instances of a given app in .NET?

Normally it's done with a named Mutex (use new Mutex( "your app name", true ) and check the return value), but there's also some support classes in Microsoft.VisualBasic.dll that can do it for you.

ReferenceError: document is not defined (in plain JavaScript)

Try adding the script element just before the /body tag like that

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>

    <div id="divid">Next</div>
    <script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>

combining results of two select statements

Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:

WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
    SELECT tableA.Id, COUNT(tableC.Id)
    FROM tableC
        RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
    GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
                     CompanyImageUrl,NumberOfUsers) AS (
    SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
        tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
    FROM tableA
        INNER JOIN tableB ON tableB.Id = tableA.Owner
        RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
    GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
    ,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
    INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id

After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.

JQuery Calculate Day Difference in 2 date textboxes

  var days=0;
  function myfunc(){
      var start= $("#firstDate").datepicker("getDate");
      var end= $("#secondDate").datepicker("getDate");
      days = (end- start) / (1000 * 60 * 60 * 24);
      alert(Math.round(days));
  }

How do I create/edit a Manifest file?

In Visual Studio 2010 (until 2019 and possibly future versions) you can add the manifest file to your project.

Right click your project file on the Solution Explorer, select Add, then New item (or CTRL+SHIFT+A). There you can find Application Manifest File.

The file name is app.manifest.

Performance of Java matrix math libraries?

I can't really comment on specific libraries, but in principle there's little reason for such operations to be slower in Java. Hotspot generally does the kinds of things you'd expect a compiler to do: it compiles basic math operations on Java variables to corresponding machine instructions (it uses SSE instructions, but only one per operation); accesses to elements of an array are compiled to use "raw" MOV instructions as you'd expect; it makes decisions on how to allocate variables to registers when it can; it re-orders instructions to take advantage of processor architecture... A possible exception is that as I mentioned, Hotspot will only perform one operation per SSE instruction; in principle you could have a fantastically optimised matrix library that performed multiple operations per instruction, although I don't know if, say, your particular FORTRAN library does so or if such a library even exists. If it does, there's currently no way for Java (or at least, Hotspot) to compete with that (though you could of course write your own native library with those optimisations to call from Java).

So what does all this mean? Well:

  • in principle, it is worth hunting around for a better-performing library, though unfortunately I can't recomend one
  • if performance is really critical to you, I would consider just coding your own matrix operations, because you may then be able perform certain optimisations that a library generally can't, or that a particular library your using doesn't (if you have a multiprocessor machine, find out if the library is actually multithreaded)

A hindrance to matrix operations is often data locality issues that arise when you need to traverse both row by row and column by column, e.g. in matrix multiplication, since you have to store the data in an order that optimises one or the other. But if you hand-write the code, you can sometimes combine operations to optimise data locality (e.g. if you're multiplying a matrix by its transformation, you can turn a column traversal into a row traversal if you write a dedicated function instead of combining two library functions). As usual in life, a library will give you non-optimal performance in exchange for faster development; you need to decide just how important performance is to you.

How to check for a Null value in VB.NET

You have to check to ensure editTransactionRow is not null and pay_id is not null.

What is callback in Android?

Here is a nice tutorial, which describes callbacks and the use-case well.

The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you".

Here's a example:

class A implements ICallback {
     MyObject o;
     B b = new B(this, someParameter);

     @Override
     public void callback(MyObject o){
           this.o = o;
     }
}

class B {
     ICallback ic;
     B(ICallback ic, someParameter){
         this.ic = ic;
     }

    new Thread(new Runnable(){
         public void run(){
             // some calculation
             ic.callback(myObject)
         }
    }).start(); 
}

interface ICallback{
    public void callback(MyObject o);
}

Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available.

In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity.

Finding sum of elements in Swift array

How about the simple way of

for (var i = 0; i < n; i++) {
 sum = sum + Int(multiples[i])!
}

//where n = number of elements in the array

How to filter by object property in angularJS

You can try this. its working for me 'name' is a property in arr.

repeat="item in (tagWordOptions | filter:{ name: $select.search } ) track by $index

Where is SQLite database stored on disk?

When you call sqlite3_open() you specify the filepath the database is opened from/saved to, if it is not an absolute path it is specified relative to your current working directory.

Granting Rights on Stored Procedure to another user of Oracle

Packages and stored procedures in Oracle execute by default using the rights of the package/procedure OWNER, not the currently logged on user.

So if you call a package that creates a user for example, its the package owner, not the calling user that needs create user privilege. The caller just needs to have execute permission on the package.

If you would prefer that the package should be run using the calling user's permissions, then when creating the package you need to specify AUTHID CURRENT_USER

Oracle documentation "Invoker Rights vs Definer Rights" has more information http://docs.oracle.com/cd/A97630_01/appdev.920/a96624/08_subs.htm#18575

Hope this helps.

Select mySQL based only on month and year

Suppose you have a database field created_at Where you take value from timestamp. You want to search by Year & Month from created_at date.

YEAR(date(created_at))=2019 AND MONTH(date(created_at))=2

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

I don't think other answers explained the key part: why "COUNT(*)" returns more than one result?

I just encountered the same issue today, and what I found out is that if you have another class extending the target mapped class (here "CustomerData"), Hibernate will do this magic.

Hope this will save some time for other unfortunate guys.

Giving graphs a subtitle in matplotlib

Just use TeX ! This works :

title(r"""\Huge{Big title !} \newline \tiny{Small subtitle !}""")

EDIT: To enable TeX processing, you need to add the "usetex = True" line to matplotlib parameters:

fig_size = [12.,7.5]
params = {'axes.labelsize': 8,
      'text.fontsize':   6,
      'legend.fontsize': 7,
      'xtick.labelsize': 6,
      'ytick.labelsize': 6,
      'text.usetex': True,       # <-- There 
      'figure.figsize': fig_size,
      }
rcParams.update(params)

I guess you also need a working TeX distribution on your computer. All details are given at this page:

http://matplotlib.org/users/usetex.html

How can I pass a parameter in Action?

Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.

this.Include(includes, () =>
{
    _context.Cars.Include(<parameters>);
});

How can I use JavaScript in Java?

I just wanted to answer something new for this question - J2V8.

Author Ian Bull says "Rhino and Nashorn are two common JavaScript runtimes, but these did not meet our requirements in a number of areas:

Neither support ‘Primitives‘. All interactions with these platforms require wrapper classes such as Integer, Double or Boolean. Nashorn is not supported on Android. Rhino compiler optimizations are not supported on Android. Neither engines support remote debugging on Android.""

Highly Efficient Java & JavaScript Integration

Github link

C/C++ maximum stack size of program

In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm.

Most compilers including Visual Studio let you specify the stack size. On some (all?) linux flavours the stack size isn't part of the executable but an environment variable in the OS. You can then check the stack size with ulimit -s and set it to a new value with for example ulimit -s 16384.

Here's a link with default stack sizes for gcc.

DFS without recursion:

std::stack<Node> dfs;
dfs.push(start);
do {
    Node top = dfs.top();
    if (top is what we are looking for) {
       break;
    }
    dfs.pop();
    for (outgoing nodes from top) {
        dfs.push(outgoing node);
    }
} while (!dfs.empty())

Best practice to run Linux service as a different user

Some things to watch out for:

  • As you mentioned, su will prompt for a password if you are already the target user
  • Similarly, setuid(2) will fail if you are already the target user (on some OSs)
  • setuid(2) does not install privileges or resource controls defined in /etc/limits.conf (Linux) or /etc/user_attr (Solaris)
  • If you go the setgid(2)/setuid(2) route, don't forget to call initgroups(3) -- more on this here

I generally use /sbin/su to switch to the appropriate user before starting daemons.

Get SSID when WIFI is connected

This is a follow up to the answer given by @EricWoodruff.

You could use netInfo's getExtraInfo() to get wifi SSID.

if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals (action)) {
    NetworkInfo netInfo = intent.getParcelableExtra (WifiManager.EXTRA_NETWORK_INFO);
    if (ConnectivityManager.TYPE_WIFI == netInfo.getType ()) {
        String ssid = info.getExtraInfo()
        Log.d(TAG, "WiFi SSID: " + ssid)
    }
}

If you are not using BroadcastReceiver check this answer to get SSID using Context

This is tested on Android Oreo 8.1.0

Is it possible to put a ConstraintLayout inside a ScrollView?

Try adding android:fillViewport="true" to the ScrollView.

Found the solution here: LinearLayout not expanding inside a ScrollView

How do you modify a CSS style in the code behind file for divs in ASP.NET?

Another way to do it:

testSpace.Style.Add("display", "none");

or

testSpace.Style["background-image"] = "url(images/foo.png)";

in vb.net you can do it this way:

testSpace.Style.Item("display") = "none"

Multiline input form field using Bootstrap

I think the problem is that you are using type="text" instead of textarea. What you want is:

<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>

To clarify, a type="text" will always be one row, where-as a textarea can be multiple.

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

I found a very interesting issue with Android Studio and the mircrosoft upgrade to the web browser. I upgraded "stupidly" to the latest version of ie. of course Microsoft in their infinite wisdom knows exactly what to do with security. When I tried to compile my app I kept getting the error Gradle - build fails -- Execution failed for task. looking in the stack I saw that it did not recognize the path to java.exe. I found that odd as I was just able to compile the day before. I added JAVA_HOME to the env vars for the system, closed Android Studio and reopened it. Low and behold if the fire wall nag screen did not pop asking if I wanted to all jave.exe through.

What a cluster!

What are the JavaScript KeyCodes?

I needed something like this for a game's control configuration UI, so I compiled a list for the standard US keyboard layout keycodes and mapped them to their respective key names.

Here's a fiddle that contains a map for code -> name and visi versa: http://jsfiddle.net/vWx8V/

If you want to support other key layouts you'll need to modify these maps to accommodate for them separately.

That is unless you were looking for a list of keycode values that included the control characters and other special values that are not (or are rarely) possible to input using a keyboard and may be outside of the scope of the keydown/keypress/keyup events of Javascript. Many of them are control characters or special characters like null (\0) and you most likely won't need them.

Notice that the number of keys on a full keyboard is less than many of the keycode values.

Default SecurityProtocol in .NET 4.5

Microsoft recently published best practices around this. https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls

Summary

Target .Net Framework 4.7, remove any code setting the SecurityProtocol, thus the OS will ensure you use the most secure solution.

NB: You will also need to ensure that the latest version of TLS is supported & enabled on your OS.

OS                          TLS 1.2 support

Windows 10                  \_ Supported, and enabled by default.
Windows Server 2016         /   
Windows 8.1                 \_ Supported, and enabled by default.
Windows Server 2012 R2      /
Windows 8.0                 \_ Supported, and enabled by default.
Windows Server 2012         /
Windows 7 SP1               \_ Supported, but not enabled by default*.
Windows Server 2008 R2 SP1  /
Windows Server 2008         -  Support for TLS 1.2 and TLS 1.1 requires an update. See Update to add support for TLS 1.1 and TLS 1.2 in Windows Server 2008 SP2.
Windows Vista               -  Not supported.

* To enable TLS1.2 via the registry see https://docs.microsoft.com/en-us/windows-server/security/tls/tls-registry-settings#tls-12 

    Path: HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS1.2\Server

        Property: Enabled
        Type: REG_DWORD
        Value: 1

        Property: DisabledByDefault 
        Type: REG_DWORD
        Value: 0

    Path: HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS1.2\Client

        Property: Enabled
        Type: REG_DWORD
        Value: 1

        Property: DisabledByDefault 
        Type: REG_DWORD
        Value: 0

For more information and older frameworks, please refer to the MS link.

CSS transition between left -> right and top -> bottom positions

This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.

topleft {
  top: 0%;
  left: 0%;
}
bottomright {
  top: 100%;
  left: 100%;
  -webkit-transform: translate(-100%,-100%);
}

select from one table, insert into another table oracle sql query

try this query below:

Insert into tab1 (tab1.column1,tab1.column2) 
select tab2.column1, 'hard coded  value' 
from tab2 
where tab2.column='value';

Android: How to turn screen on and off programmatically?

I had written this method to turn on the screen after screen lock. It works perfectly for me. Try it-

    private void unlockScreen() {
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }

And call this method from onResume().

What's the best way to select the minimum value from several columns?

Below I use a temp table to get the minimum of several dates. The first temp table queries several joined tables to get various dates (as well as other values for the query), the second temp table then gets the various columns and the minimum date using as many passes as there are date columns.

This is essentially like the union query, the same number of passes are required, but may be more efficient (based on experience, but would need testing). Efficiency wasn't an issue in this case (8,000 records). One could index etc.

--==================== this gets minimums and global min
if object_id('tempdb..#temp1') is not null
    drop table #temp1
if object_id('tempdb..#temp2') is not null
    drop table #temp2

select r.recordid ,  r.ReferenceNumber, i.InventionTitle, RecordDate, i.ReceivedDate
, min(fi.uploaddate) [Min File Upload], min(fi.CorrespondenceDate) [Min File Correspondence]
into #temp1
from record r 
join Invention i on i.inventionid = r.recordid
left join LnkRecordFile lrf on lrf.recordid = r.recordid
left join fileinformation fi on fi.fileid = lrf.fileid
where r.recorddate > '2015-05-26'
 group by  r.recordid, recorddate, i.ReceivedDate,
 r.ReferenceNumber, i.InventionTitle



select recordid, recorddate [min date]
into #temp2
from #temp1

update #temp2
set [min date] = ReceivedDate 
from #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid
where t1.ReceivedDate < [min date] and  t1.ReceivedDate > '2001-01-01'

update #temp2 
set [min date] = t1.[Min File Upload]
from #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid
where t1.[Min File Upload] < [min date] and  t1.[Min File Upload] > '2001-01-01'

update #temp2
set [min date] = t1.[Min File Correspondence]
from #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid
where t1.[Min File Correspondence] < [min date] and t1.[Min File Correspondence] > '2001-01-01'


select t1.*, t2.[min date] [LOWEST DATE]
from #temp1 t1 join #temp2 t2 on t1.recordid = t2.recordid
order by t1.recordid

How can I include all JavaScript files in a directory via JavaScript file?

Given that you want a 100% client side solution, in theory you could probably do this:

Via XmlHttpRequest, get the directory listing page for that directory (most web servers return a listing of files if there is no index.html file in the directory).

Parse that file with javascript, pulling out all the .js files. This will of course be sensitive to the format of the directory listing on your web server / web host.

Add the script tags dynamically, with something like this:

function loadScript (dir, file) {
 var scr = document.createElement("script");
 scr.src = dir + file;
 document.body.appendChild(scr);
 }

how to fetch data from database in Hibernate

Query query = session.createQuery("from Employee");

Note: from Employee. here Employee is not your table name it's POJO name.

Reliable and fast FFT in Java

Late to the party - here as a pure java solution for those when JNI is not an option.JTransforms

Check if table exists without using "select from"

You can query the INFORMATION_SCHEMA tables system view:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';

If no rows returned, then the table doesn't exist.

How to remove trailing whitespace in code, using another script?

You don't see any output from the print statements because FileInput redirects stdout to the input file when the keyword argument inplace=1 is given. This causes the input file to effectively be rewritten and if you look at it afterwards the lines in it will indeed have no trailing or leading whitespace in them (except for the newline at the end of each which the print statement adds back).

If you only want to remove trailing whitespace, you should use rstrip() instead of strip(). Also note that the if lines == '': continue is causing blank lines to be completely removed (regardless of whether strip or rstrip gets used).

Unless your intent is to rewrite the input file, you should probably just use for line in open(filename):. Otherwise you can see what's being written to the file by simultaneously echoing the output to sys.stderr using something like the following:

import fileinput
import sys

for line in (line.rstrip() for line in
                fileinput.FileInput("test.txt", inplace=1)):
    if line:
        print line
        print >>sys.stderr, line

Anaconda version with Python 3.5

It is very simple, first, you need to be inside the virtualenv you created, then to install a specific version of python say 3.5, use Anaconda, conda install python=3.5

In general you can do this for any python package you want

conda install package_name=package_version

How to hide scrollbar in Firefox?

I used this and it worked. https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width

html {
scrollbar-width: none;
}

Note: User Agents must apply any scrollbar-width value set on the root element to the viewport.

Split (explode) pandas dataframe string entry to separate rows

There is a possibility to split and explode the dataframe without changing the structure of dataframe

Split and expand data of specific columns

Input:

    var1    var2
0   a,b,c   1
1   d,e,f   2



#Get the indexes which are repetative with the split 
df['var1'] = df['var1'].str.split(',')
df = df.explode('var1')

Out:

    var1    var2
0   a   1
0   b   1
0   c   1
1   d   2
1   e   2
1   f   2

Edit-1

Split and Expand of rows for Multiple columns

Filename    RGB                                             RGB_type
0   A   [[0, 1650, 6, 39], [0, 1691, 1, 59], [50, 1402...   [r, g, b]
1   B   [[0, 1423, 16, 38], [0, 1445, 16, 46], [0, 141...   [r, g, b]

Re indexing based on the reference column and aligning the column value information with stack

df = df.reindex(df.index.repeat(df['RGB_type'].apply(len)))
df = df.groupby('Filename').apply(lambda x:x.apply(lambda y: pd.Series(y.iloc[0])))
df.reset_index(drop=True).ffill()

Out:

                Filename    RGB_type    Top 1 colour    Top 1 frequency Top 2 colour    Top 2 frequency
    Filename                            
 A  0       A   r   0   1650    6   39
    1       A   g   0   1691    1   59
    2       A   b   50  1402    49  187
 B  0       B   r   0   1423    16  38
    1       B   g   0   1445    16  46
    2       B   b   0   1419    16  39

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

Do not attempt to remove any Apple-supplied system Python which are in /System/Library and /usr/bin, as this may break your whole operating system.


NOTE: The steps listed below do not affect the Apple-supplied system Python 2.7; they only remove a third-party Python framework, like those installed by python.org installers.


The complete list is documented here. Basically, all you need to do is the following:

  1. Remove the third-party Python 2.7 framework

    sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7
    
  2. Remove the Python 2.7 applications directory

    sudo rm -rf "/Applications/Python 2.7"
    
  3. Remove the symbolic links, in /usr/local/bin, that point to this Python version. See them using

    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' 
    

    and then run the following command to remove all the links:

    cd /usr/local/bin/
    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm
    
  4. If necessary, edit your shell profile file(s) to remove adding /Library/Frameworks/Python.framework/Versions/2.7 to your PATH environment file. Depending on which shell you use, any of the following files may have been modified: ~/.bash_login, ~/.bash_profile, ~/.cshrc, ~/.profile, ~/.tcshrc, and/or ~/.zprofile.

Check whether $_POST-value is empty

To check if the property is present, irrespective of the value, use:

if (array_key_exists('userName', $_POST)) {}

To check if the property is set (property is present and value is not null or false), use:

if (isset($_POST['userName'])) {}

To check if the property is set and not empty (not an empty string, 0 (integer), 0.0 (float), '0' (string), null, false or [] (empty array)), use:

if (!empty($_POST['userName'])) {}

Map enum in JPA with fixed values?

From JPA 2.1 you can use AttributeConverter.

Create an enumerated class like so:

public enum NodeType {

    ROOT("root-node"),
    BRANCH("branch-node"),
    LEAF("leaf-node");

    private final String code;

    private NodeType(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

And create a converter like this:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class NodeTypeConverter implements AttributeConverter<NodeType, String> {

    @Override
    public String convertToDatabaseColumn(NodeType nodeType) {
        return nodeType.getCode();
    }

    @Override
    public NodeType convertToEntityAttribute(String dbData) {
        for (NodeType nodeType : NodeType.values()) {
            if (nodeType.getCode().equals(dbData)) {
                return nodeType;
            }
        }

        throw new IllegalArgumentException("Unknown database value:" + dbData);
    }
}

On the entity you just need:

@Column(name = "node_type_code")

You luck with @Converter(autoApply = true) may vary by container but tested to work on Wildfly 8.1.0. If it doesn't work you can add @Convert(converter = NodeTypeConverter.class) on the entity class column.

Why is Tkinter Entry's get function returning nothing?

you need to put a textvariable in it, so you can use set() and get() method :

var=StringVar()
x= Entry (root,textvariable=var)

jQuery - trapping tab select event

In later versions of JQuery they have changed the function from select to activate. http://api.jqueryui.com/tabs/#event-activate

Timestamp with a millisecond precision: How to save them in MySQL

You can use BIGINT as follows:

CREATE TABLE user_reg (
user_id INT NOT NULL AUTO_INCREMENT,
identifier INT,
phone_number CHAR(11) NOT NULL,
verified TINYINT UNSIGNED NOT NULL,
reg_time BIGINT,
last_active_time BIGINT,
PRIMARY KEY (user_id),
INDEX (phone_number, user_id, identifier)
   );

Javascript checkbox onChange

HTML:

<input type="checkbox" onchange="handleChange(event)">

JS:

function handleChange(e) {
     const {checked} = e.target;
}

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

How do I import a namespace in Razor View Page?

You can try this

@using MyNamespace

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

Print in one line dynamically

A comma at the end of the print statement omits the new line.

for i in xrange(1,100):
  print i,

but this does not overwrite.