Programs & Examples On #Xrm

xRM is an alternative term used to market Microsoft Dynamics CRM. Generally, unless the question deals with those marketing differences, questions should not be tagged here.

AttributeError: 'list' object has no attribute 'encode'

You need to do encode on tmp[0], not on tmp.

tmp is not a string. It contains a (Unicode) string.

Try running type(tmp) and print dir(tmp) to see it for yourself.

Manually Triggering Form Validation using jQuery

For input field

<input id="PrimaryPhNumber" type="text" name="mobile"  required
                                       pattern="^[789]\d{9}$" minlenght="10" maxLength="10" placeholder="Eg: 9444400000"
                                       class="inputBoxCss"/>
$('#PrimaryPhNumber').keyup(function (e) {
        console.log(e)
        let field=$(this)
        if(Number(field.val()).toString()=="NaN"){
            field.val('');
            field.focus();
            field[0].setCustomValidity('Please enter a valid phone number');
            field[0].reportValidity()
            $(":focus").css("border", "2px solid red");
        }
    })

Import Excel Data into PostgreSQL 9.3

For python you could use openpyxl for all 2010 and newer file formats (xlsx).

Al Sweigart has a full tutorial from automate the boring parts on working with excel spreadsheets its very indepth and the whole book and accompanying Udemy course are great resources.

From his example

>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">

Understandably once you have this access you can now use psycopg to parse the data to postgres as you normally would do.

This is a link to a list of python resources at python-excel also xlwings provides a large array of features for using python in place of vba in excel.

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Retrofit and GET using parameters

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {

private static final String BASEPATH = "http://www.example.com";

private interface API {
    @GET("/thing")
    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.your_layout);

   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
   API service = rest.create(API.class);

   Map<String, String> params = new HashMap<String, String>();
   params.put("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.
   });
}
}

The URL called will be http://www.example.com/thing/?key1=val1&key2=val2

JQuery/Javascript: check if var exists

Before each of your conditional statements, you could do something like this:

var pagetype = pagetype || false;
if (pagetype === 'something') {
    //do stuff
}

How to get evaluated attributes inside a custom directive

For an attribute value that needs to be interpolated in a directive that is not using an isolated scope, e.g.,

<input my-directive value="{{1+1}}">

use Attributes' method $observe:

myApp.directive('myDirective', function () {
  return function (scope, element, attr) {
    attr.$observe('value', function(actual_value) {
      element.val("value = "+ actual_value);
    })
 }
});

From the directive page,

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

If the attribute value is just a constant, e.g.,

<input my-directive value="123">

you can use $eval if the value is a number or boolean, and you want the correct type:

return function (scope, element, attr) {
   var number = scope.$eval(attr.value);
   console.log(number, number + 1);
});

If the attribute value is a string constant, or you want the value to be string type in your directive, you can access it directly:

return function (scope, element, attr) {
   var str = attr.value;
   console.log(str, str + " more");
});

In your case, however, since you want to support interpolated values and constants, use $observe.

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

How to convert List<string> to List<int>?

Using Linq:

var intList = stringList.Select(s => Convert.ToInt32(s)).ToList()

How can I measure the actual memory usage of an application or process?

#!/bin/ksh
#
# Returns total memory used by process $1 in kb.
#
# See /proc/NNNN/smaps if you want to do something
# more interesting.
#

IFS=$'\n'

for line in $(</proc/$1/smaps)
do
   [[ $line =~ ^Size:\s+(\S+) ]] && ((kb += ${.sh.match[1]}))
done

print $kb

How to select a single field for all documents in a MongoDB collection?

The query for MongoDB here fees is collection and description is a field.

db.getCollection('fees').find({},{description:1,_id:0})

JavaScript REST client Library

You can use this jQuery plugin I just made :) https://github.com/jpillora/jquery.rest/

Supports basic CRUD operations, nested resources, basic auth

  var client = new $.RestClient('/api/rest/');

  client.add('foo');
  client.foo.add('baz');
  client.add('bar');

  client.foo.create({a:21,b:42});
  // POST /api/rest/foo/ (with data a=21 and b=42)
  client.foo.read();
  // GET /api/rest/foo/
  client.foo.read("42");
  // GET /api/rest/foo/42/
  client.foo.update("42");
  // PUT /api/rest/foo/42/
  client.foo.delete("42");
  // DELETE /api/rest/foo/42/

  //RESULTS USE '$.Deferred'
  client.foo.read().success(function(foos) {
    alert('Hooray ! I have ' + foos.length + 'foos !' );
  });

If you find bugs or want new features, post them in the repositories 'Issues' page please

Create a folder if it doesn't already exist

Faster way to create folder:

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}

iOS 6 apps - how to deal with iPhone 5 screen size?

No.

if ([[UIScreen mainScreen] bounds].size.height > 960)

on iPhone 5 is wrong

if ([[UIScreen mainScreen] bounds].size.height == 568)

Checking if a folder exists (and creating folders) in Qt, C++

When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.

You can see more on Qt Documentation

How can I correctly format currency using jquery?

Try regexp currency with jQuery (no plugin):

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('#test').click(function() {_x000D_
    TESTCURRENCY = $('#value').val().toString().match(/(?=[\s\d])(?:\s\.|\d+(?:[.]\d+)*)/gmi);_x000D_
    if (TESTCURRENCY.length <= 1) {_x000D_
      $('#valueshow').val(_x000D_
        parseFloat(TESTCURRENCY.toString().match(/^\d+(?:\.\d{0,2})?/))_x000D_
      );_x000D_
    } else {_x000D_
      $('#valueshow').val('Invalid a value!');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="text" value="12345.67890" id="value">_x000D_
<input type="button" id="test" value="CLICK">_x000D_
<input type="text" value="" id="valueshow">
_x000D_
_x000D_
_x000D_

Edit: New check a value to valid/invalid

check if jquery has been loaded, then load it if false

Method 1:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

Method 2:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

If jquery.js file is not loaded, we can force load it like so:

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

Custom header to HttpClient request

There is a Headers property in the HttpRequestMessage class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders in the HttpClient class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.

Hope this makes things more clear, at least for someone seeing this answer in future.

Escaping Strings in JavaScript

You can also use this

_x000D_
_x000D_
let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
_x000D_
_x000D_

Unix command-line JSON parser?

Checkout TickTick.

It's a true Bash JSON parser.

#!/bin/bash
. /path/to/ticktick.sh

# File
DATA=`cat data.json`
# cURL
#DATA=`curl http://foobar3000.com/echo/request.json`

tickParse "$DATA"

echo ``pathname``
echo ``headers["user-agent"]``

Can't get value of input type="file"?

You can't set the value of a file input in the markup, like you did with value="123".

This example shows that it really works: http://jsfiddle.net/marcosfromero/7bUba/

Launch Bootstrap Modal on page load

Just add the following-

class="modal show"

Working Example-

_x000D_
_x000D_
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal show" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Where is the WPF Numeric UpDown control?

I made my own;

the xaml

<StackPanel Orientation="Horizontal">
    <TextBox x:Name="txtNum" x:FieldModifier="private" Margin="5,5,0,5" Width="50" Text="0" TextChanged="txtNum_TextChanged" />
    <Button x:Name="cmdUp" x:FieldModifier="private" Margin="5,5,0,5" Content="^" Width="20" Click="cmdUp_Click" />
    <Button x:Name="cmdDown" x:FieldModifier="private" Margin="0,5,0,5"  Content="?" Width="20" Click="cmdDown_Click" />
</StackPanel>

and the code behind

private int _numValue = 0;

public int NumValue
{
    get {  return _numValue; }
    set
    {
        _numValue = value;
        txtNum.Text = value.ToString();
    }
}

public NumberUpDown()
{
    InitializeComponent();
    txtNum.Text = _numValue.ToString();
}

private void cmdUp_Click(object sender, RoutedEventArgs e)
{
    NumValue++;
}

private void cmdDown_Click(object sender, RoutedEventArgs e)
{
    NumValue--;
}

private void txtNum_TextChanged(object sender, TextChangedEventArgs e)
{
    if (txtNum == null)
    {
        return;
    }

    if (!int.TryParse(txtNum.Text, out _numValue))
        txtNum.Text = _numValue.ToString();
}

Volley JsonObjectRequest Post request not working

All you need to do is to override getParams method in Request class. I had the same problem and I searched through the answers but I could not find a proper one. The problem is unlike get request, post parameters being redirected by the servers may be dropped. For instance, read this. So, don't risk your requests to be redirected by webserver. If you are targeting http://example/myapp , then mention the exact address of your service, that is http://example.com/myapp/index.php.
Volley is OK and works perfectly, the problem stems from somewhere else.

How to call codeigniter controller function from view

class MY_Controller extends CI_Controller {

    public $CI = NULL;

    public function __construct() {
        parent::__construct();
        $this->CI = & get_instance();
    }

    public function yourMethod() {

    }

}

// in view just call
$this->CI->yourMethod();

How do I programmatically change file permissions?

Just to update this answer unless anyone comes across this later, since JDK 6 you can use

File file = new File('/directory/to/file');
file.setWritable(boolean);
file.setReadable(boolean);
file.setExecutable(boolean);

you can find the documentation on Oracle File(Java Platform SE 7). Bear in mind that these commands only work if the current working user has ownership or write access to that file. I am aware that OP wanted chmod type access for more intricate user configuration. these will set the option across the board for all users.

Factorial using Recursion in Java

Using Java 8 and above, using recursion itself

  UnaryOperator<Long> fact = num -> num<1 ? 1 : num * this.fact.apply(num-1);

And use it like

  fact.apply(5); // prints 120

Internally it calculate like

5*(4*(3*(2*(1*(1)))))

Make scrollbars only visible when a Div is hovered over?

One trick for this, for webkit browsers, is to create an invisible scrollbar, and then make it appear on hover. This method does not affect the scrolling area width as the space needed for the scrollbar is already there.

Something like this:

_x000D_
_x000D_
body {_x000D_
  height: 500px;_x000D_
  &::-webkit-scrollbar {_x000D_
    background-color: transparent;_x000D_
    width: 10px;_x000D_
  }_x000D_
  &::-webkit-scrollbar-thumb {_x000D_
    background-color: transparent;_x000D_
  }_x000D_
}_x000D_
_x000D_
body:hover {_x000D_
  &::-webkit-scrollbar-thumb {_x000D_
    background-color: black;_x000D_
  }_x000D_
}_x000D_
_x000D_
.full-width {_x000D_
  width: 100%;_x000D_
  background: blue;_x000D_
  padding: 30px;_x000D_
  color: white;_x000D_
}
_x000D_
some content here_x000D_
_x000D_
<div class="full-width">does not change</div>
_x000D_
_x000D_
_x000D_

Make EditText ReadOnly

This works for me:

EditText.setKeyListener(null);

C# Return Different Types?

To build on the answer by @RQDQ using generics, you can combine this with Func<TResult> (or some variation) and delegate responsibility to the caller:

public T GetAnything<T>(Func<T> createInstanceOfT)
{
    //do whatever

    return createInstanceOfT();
}

Then you can do something like:

Computer comp = GetAnything(() => new Computer());
Radio rad = GetAnything(() => new Radio());

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

In Python, how do I loop through the dictionary and change the value if it equals something?

Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration:

mydict = dict((k, v if v else '') for k, v in mydict.items())

How can I see the request headers made by curl when sending a request to the server?

curl -s -v -o/dev/null -H "Testheader: test" http://www.example.com

You could also use -I option if you want to send a HEAD request and not a GET request.

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

Go to command prompt, cd to the appropriate folder and type:

notepad .htaccess

After confirmation dialog the file will be created and you will be editing it directly. If you just want to create an empty file, try

echo. > .htaccess

Select SQL results grouped by weeks

Base on @increddibelly answer, I applied to my query as below.

I share for whom concerned.

My table structure FamilyData(Id, nodeTime, totalEnergy)

select
   sum(totalEnergy) as TotalEnergy,
   DATEPART ( week, nodeTime ) as weeknr
from FamilyData
group by DATEPART (week, nodeTime)

Using DISTINCT inner join in SQL

I believe your 1:m relationships should already implicitly create DISTINCT JOINs.

But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.

SELECT DISTINCT a.valueA, c.valueC
FROM C
    INNER JOIN B ON B.lookupC = C.id
    INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

Reporting Services Remove Time from DateTime in Expression

I'm coming late in the game but I tried all of the solutions above! couldn't get it to drop the zero's in the parameter and give me a default (it ignored the formatting or appeared blank). I was using SSRS 2005 so was struggling with its clunky / buggy issues.

My workaround was to add a column to the custom [DimDate] table in my database that I was pulling dates from. I added a column that was a string representation in the desired format of the [date] column. I then created 2 new Datasets in SSRS that pulled in the following queries for 2 defaults for my 'To' & 'From' date defaults -

'from'

    SELECT  Datestring
    FROM    dbo.dimDate
    WHERE   [date] = ( SELECT   MAX(date)
                       FROM     dbo.dimdate
                       WHERE    date < DATEADD(month, -3, GETDATE()
                     )

'to'

    SELECT  Datestring
    FROM    dbo.dimDate
    WHERE   [date] = ( SELECT   MAX(date)
                       FROM     dbo.dimdate
                       WHERE    date <= GETDATE()
                     )

What is the difference between Digest and Basic Authentication?

Digest Authentication communicates credentials in an encrypted form by applying a hash function to: the username, the password, a server supplied nonce value, the HTTP method and the requested URI.

Whereas Basic Authentication uses non-encrypted base64 encoding.

Therefore, Basic Authentication should generally only be used where transport layer security is provided such as https.

See RFC-2617 for all the gory details.

How to extract week number in sql

Use 'dd-mon-yyyy' if you are using the 2nd date format specified in your answer. Ex:

to_date(<column name>,'dd-mon-yyyy')

write() versus writelines() and concatenated strings

Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).

nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)

should work.

How to handle Pop-up in Selenium WebDriver using Java

You can handle popup window or alert box:

Alert alert = driver.switchTo().alert();
alert.accept();

You can also decline the alert box:

Alert alert = driver.switchTo().alert();
alert().dismiss();

How to run shell script on host from docker container?

My laziness led me to find the easiest solution that wasn't published as an answer here.

It is based on the great article by luc juggery.

All you need to do in order to gain a full shell to your linux host from within your docker container is:

docker run --privileged --pid=host -it alpine:3.8 \
nsenter -t 1 -m -u -n -i sh

Explanation:

--privileged : grants additional permissions to the container, it allows the container to gain access to the devices of the host (/dev)

--pid=host : allows the containers to use the processes tree of the Docker host (the VM in which the Docker daemon is running) nsenter utility: allows to run a process in existing namespaces (the building blocks that provide isolation to containers)

nsenter (-t 1 -m -u -n -i sh) allows to run the process sh in the same isolation context as the process with PID 1. The whole command will then provide an interactive sh shell in the VM

This setup has major security implications and should be used with cautions (if any).

Smooth scrolling when clicking an anchor link

$("a").on("click", function(event){
    //check the value of this.hash
    if(this.hash !== ""){
        event.preventDefault();

        $("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);

        //add hash to the current scroll position
        window.location.hash = this.hash;

    }



});

Check if xdebug is working

Starting with xdebug 3 you can use the following command line :

php -r "xdebug_info();"

And it will display useful information about your xdebug installation.

How to check status of PostgreSQL server Mac OS X

You can use brew to start/stop pgsql. I've following short cuts in my ~/.bashrc file

alias start-pg='brew services start postgresql'
alias stop-pg='brew services stop postgresql'
alias restart-pg='brew services restart postgresql'

How to get the list of files in a directory in a shell script?

The accepted answer will not return files prefix with a . To do that use

for entry in "$search_dir"/* "$search_dir"/.[!.]* "$search_dir"/..?*
do
  echo "$entry"
done

Convert DataTable to IEnumerable<T>

        PagedDataSource objPage = new PagedDataSource();

        DataView dataView = listData.DefaultView;
        objPage.AllowPaging = true;
        objPage.DataSource = dataView;
        objPage.PageSize = PageSize;

        TotalPages = objPage.PageCount;

        objPage.CurrentPageIndex = CurrentPage - 1;

        //Convert PagedDataSource to DataTable
        System.Collections.IEnumerator pagedData = objPage.GetEnumerator();

        DataTable filteredData = new DataTable();
        bool flagToCopyDTStruct = false;
        while (pagedData.MoveNext())
        {
            DataRowView rowView = (DataRowView)pagedData.Current;
            if (!flagToCopyDTStruct)
            {
                filteredData = rowView.Row.Table.Clone();
                flagToCopyDTStruct = true;
            }
            filteredData.LoadDataRow(rowView.Row.ItemArray, true);
        }

        //Here is your filtered DataTable
        return filterData; 

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

How to check "hasRole" in Java Code with Spring Security?

You can retrieve the security context and then use that:

    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.context.SecurityContext;
    import org.springframework.security.core.context.SecurityContextHolder;

    protected boolean hasRole(String role) {
        // get security context from thread local
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null)
            return false;

        Authentication authentication = context.getAuthentication();
        if (authentication == null)
            return false;

        for (GrantedAuthority auth : authentication.getAuthorities()) {
            if (role.equals(auth.getAuthority()))
                return true;
        }

        return false;
    }

Using .text() to retrieve only text not nested in child tags

Use an extra condition to check if innerHTML and innerText are the same. Only in those cases, replace the text.

$(function() {
$('body *').each(function () {
    console.log($(this).html());
    console.log($(this).text());
    if($(this).text() === "Search" && $(this).html()===$(this).text())  {
        $(this).html("Find");
    }
})
})

http://jsfiddle.net/7RSGh/

git command to move a folder inside another

Command:

$ git mv oldFolderName newFolderName

It usually works fine.

Error "bad source ..." typically indicates that after last commit there were some renames in the source directory and hence git mv cannot find the expected file.

The solution is simple - just commit before applying git mv.

How do I read input character-by-character in Java?

Wrap your input stream in a buffered reader then use the read method to read one byte at a time until the end of stream.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Reader {

    public static void main(String[] args) throws IOException {

        BufferedReader buffer = new BufferedReader(
                 new InputStreamReader(System.in));
        int c = 0;
        while((c = buffer.read()) != -1) {
            char character = (char) c;          
            System.out.println(character);          
        }       
    }   
}

How to print all information from an HTTP request to the screen, in PHP

Well, you can read the entirety of the POST body like so

echo file_get_contents( 'php://input' );

And, assuming your webserver is Apache, you can read the request headers like so

$requestHeaders = apache_request_headers();

How does @synchronized lock/unlock in Objective-C?

The Objective-C language level synchronization uses the mutex, just like NSLock does. Semantically there are some small technical differences, but it is basically correct to think of them as two separate interfaces implemented on top of a common (more primitive) entity.

In particular with a NSLock you have an explicit lock whereas with @synchronized you have an implicit lock associated with the object you are using to synchronize. The benefit of the language level locking is the compiler understands it so it can deal with scoping issues, but mechanically they behave basically the same.

You can think of @synchronized as a compiler rewrite:

- (NSString *)myString {
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

is transformed into:

- (NSString *)myString {
  NSString *retval = nil;
  pthread_mutex_t *self_mutex = LOOK_UP_MUTEX(self);
  pthread_mutex_lock(self_mutex);
  retval = [[myString retain] autorelease];
  pthread_mutex_unlock(self_mutex);
  return retval;
}

That is not exactly correct because the actual transform is more complex and uses recursive locks, but it should get the point across.

Difference between Static and final?

The two really aren't similar. static fields are fields that do not belong to any particular instance of a class.

class C {
    public static int n = 42;
}

Here, the static field n isn't associated with any particular instance of C but with the entire class in general (which is why C.n can be used to access it). Can you still use an instance of C to access n? Yes - but it isn't considered particularly good practice.

final on the other hand indicates that a particular variable cannot change after it is initialized.

class C {
    public final int n = 42;
}

Here, n cannot be re-assigned because it is final. One other difference is that any variable can be declared final, while not every variable can be declared static.

Also, classes can be declared final which indicates that they cannot be extended:

final class C {}

class B extends C {}  // error!

Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:

class C {
    public final void foo() {}
}

class B extends C {
    public void foo() {}  // error!
}

Getting RAW Soap Data from a Web Reference Client running in ASP.net

Try Fiddler2 it will let you inspect the requests and response. It might be worth noting that Fiddler works with both http and https traffic.

How to redirect the output of a PowerShell to a file during its execution

Microsoft has announced on Powershell's Connections web site (2012-02-15 at 4:40 PM) that in version 3.0 they have extended the redirection as a solution to this problem.

In PowerShell 3.0, we've extended output redirection to include the following streams: 
 Pipeline (1) 
 Error    (2) 
 Warning  (3) 
 Verbose  (4) 
 Debug    (5)
 All      (*)

We still use the same operators
 >    Redirect to a file and replace contents
 >>   Redirect to a file and append to existing content
 >&1  Merge with pipeline output

See the "about_Redirection" help article for details and examples.

help about_Redirection

VBA Excel Provide current Date in Text box

Here's a more simple version. In the cell you want the date to show up just type

=Today()      

Format the cell to the date format you want and Bob's your uncle. :)

Float to String format specifier

Use ToString() with this format:

12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000

Put as much zero as necessary at the end of the format.

How do I debug jquery AJAX calls?

if you are using mozilla firefox than just install an add-on called firebug.

In your page press f12 in mozilla and firebug will open.

go for the net tab in firebug and in this tab go in the xhr tab. and reload your page. you will get 5 options in xhr Params Headers Response HTML and Cookies

so by going in response and html you can see which response you are getting after your ajax call.

Please let me know if you have any issue.

Get exception description and stack trace which caused an exception, all as a string

With Python 3, the following code will format an Exception object exactly as would be obtained using traceback.format_exc():

import traceback

try: 
    method_that_can_raise_an_exception(params)
except Exception as ex:
    print(''.join(traceback.format_exception(etype=type(ex), value=ex, tb=ex.__traceback__)))

The advantage being that only the Exception object is needed (thanks to the recorded __traceback__ attribute), and can therefore be more easily passed as an argument to another function for further processing.

How to parse JSON in Kotlin?

There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. Version kotlinx.serialization 1.0 is finally released

https://github.com/Kotlin/kotlinx.serialization

import kotlinx.serialization.*
import kotlinx.serialization.json.JSON

@Serializable
data class MyModel(val a: Int, @Optional val b: String = "42")

fun main(args: Array<String>) {

    // serializing objects
    val jsonData = JSON.stringify(MyModel.serializer(), MyModel(42))
    println(jsonData) // {"a": 42, "b": "42"}
    
    // serializing lists
    val jsonList = JSON.stringify(MyModel.serializer().list, listOf(MyModel(42)))
    println(jsonList) // [{"a": 42, "b": "42"}]

    // parsing data back
    val obj = JSON.parse(MyModel.serializer(), """{"a":42}""")
    println(obj) // MyModel(a=42, b="42")
}

Do Facebook Oauth 2.0 Access Tokens Expire?

This is a fair few years later, but the Facebook Graph API Explorer now has a little info symbol next to the access token that allows you to access the access token tool app, and extend the API token for a couple of months. Might be helpful during development.

enter image description here

Bootstrap control with multiple "data-toggle"

HTML (ejs dianmic web page): this is a table list of all users and from nodejs generate the table. NodeJS provide dinamic "<%= user.id %>". simply change for any value like "54"

<span type="button" data-href='/admin/user/del/<%= user.id %>' class="item" 
 data-toggle="modal" data-target="#confirm_delete">
    <div data-toggle="tooltip" data-placement="top" title="Delete" data- 
     toggle="modal">
       <i class="zmdi zmdi-delete"></i> 
    </div>
</span>
<div class="modal fade" id="confirm_delete" tabindex="-1" role="dialog" aria-labelledby="staticModalLabel" aria-hidden="true"
         data-backdrop="static">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticModalLabel">Static Modal</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>
      </div>
      <div class="modal-body">
        <p> This is a static modal, backdrop click will not close it. </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <form method="POST" class="btn-ok">
            <input  type="submit" class="btn btn-danger" value="Confirm"></input>
        </form>
      </div>
    </div>
  </div>
</div>
<!-- end modal static --> 

JS:

    $(document).ready(function(){
        $('#confirm_delete').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('action', $(e.relatedTarget).data('href'));
        });
    });

Deleting Row in SQLite in Android

Try this code

public void deleteRow(String value)
{
SQLiteDatabase db = this.getWritableDatabase();       
db.execSQL("DELETE FROM " + TABLE_NAME+ " WHERE "+COlUMN_NAME+"='"+value+"'");
db.close();
}

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

How do I save a String to a text file using Java?

You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file. if something does not make sense, I'm sorry is google translator and I who do not speak English.

Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.


private void SaveActionPerformed(java.awt.event.ActionEvent evt) {

    String NameFile = Name.getText();
    ArrayList< String > Text = new ArrayList< String >();

    Text.add(TextArea.getText());

    SaveFile(NameFile, Text);
}

public void SaveFile(String name, ArrayList< String> message) {

    path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

    File file1 = new File(path);

    try {

        if (!file1.exists()) {

            file1.createNewFile();
        }


        File[] files = file1.listFiles();


        FileWriter fw = new FileWriter(file1, true);

        BufferedWriter bw = new BufferedWriter(fw);

        for (int i = 0; i < message.size(); i++) {

            bw.write(message.get(i));
            bw.newLine();
        }

        bw.close();
        fw.close();

        FileReader fr = new FileReader(file1);

        BufferedReader br = new BufferedReader(fr);

        fw = new FileWriter(file1, true);

        bw = new BufferedWriter(fw);

        while (br.ready()) {

            String line = br.readLine();

            System.out.println(line);

            bw.write(line);
            bw.newLine();

        }
        br.close();
        fr.close();

    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error in" + ex);     
    }   
}

Spring mvc @PathVariable

Let us assume you hit a url as www.example.com/test/111 . Now you have to retrieve value 111 (which is dynamic) to your controller method .At time you ll be using @PathVariable as follows :

@RequestMapping(value = " /test/{testvalue}", method=RequestMethod.GET)
public void test(@PathVariable String testvalue){
//you can use test value here
}

SO the variable value is retrieved from the url

What's the difference between a Python module and a Python package?

Any Python file is a module, its name being the file's base name without the .py extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.

The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules. As an example, consider the xml package in the Python standard library: its xml directory contains an __init__.py file and four sub-directories; the sub-directory etree contains an __init__.py file and, among others, an ElementTree.py file. See what happens when you try to interactively import package/modules:

>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>

In Python there also are built-in modules, such as sys, that are written in C, but I don't think you meant to consider those in your question.

Detect home button press in android

Jack's answer is perfectly working for click event while longClick is considering is as menu button click.

By the way, if anyone is wondering how to do via kotlin,

class HomeButtonReceiver(private var context: Context,private var listener: OnHomeButtonClickListener) {
    private val mFilter: IntentFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
    private var mReceiver: InnerReceiver = InnerReceiver()

    fun startWatch() {
        context.registerReceiver(mReceiver, mFilter)
    }

    fun stopWatch() {
        context.unregisterReceiver(mReceiver)
    }

    inner class InnerReceiver: BroadcastReceiver() {
        private val systemDialogReasonKey = "reason"
        private val systemDialogReasonHomeKey = "homekey"
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(systemDialogReasonKey)
                if (reason != null && reason == systemDialogReasonHomeKey) {
                    listener.onHomeButtonClick()
                }
            }
        }
    } 
}

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

compare differences between two tables in mysql

Based on Haim's answer here's a simplified example if you're looking to compare values that exist in BOTH tables, otherwise if there's a row in one table but not the other it will also return it....

Took me a couple of hours to figure out. Here's a fully tested simply query for comparing "tbl_a" and "tbl_b"

SELECT ID, col
FROM
(
    SELECT
    tbl_a.ID, tbl_a.col FROM tbl_a
    UNION ALL
    SELECT
    tbl_b.ID, tbl_b.col FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
 ORDER BY ID

So you need to add the extra "where in" clause:

WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)


Also:

For ease of reading if you want to indicate the table names you can use the following:

SELECT tbl, ID, col
FROM
(
    SELECT
    tbl_a.ID, tbl_a.col, "name_to_display1" as "tbl" FROM tbl_a
    UNION ALL
    SELECT
    tbl_b.ID, tbl_b.col, "name_to_display2" as "tbl" FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
 ORDER BY ID

Removing array item by value

I am adding a second answer. I wrote a quick benchmarking script to try various methods here.

$arr = array(0 => 123456);
for($i = 1; $i < 500000; $i++) {
    $arr[$i] = rand(0,PHP_INT_MAX);
}

shuffle($arr);
$arr2 = $arr;
$arr3 = $arr;

/** 
 * Method 1 - array_search()
 */
$start = microtime(true);
while(($key = array_search(123456,$arr)) !== false) {
    unset($arr[$key]);
}
echo count($arr). ' left, in '.(microtime(true) - $start).' seconds<BR>';

/** 
 * Method 2 - basic loop
 */
$start = microtime(true);
foreach($arr2 as $k => $v) {
    if ($v == 123456) {
        unset($arr2[$k]);
    }
}
echo count($arr2). 'left, in '.(microtime(true) - $start).' seconds<BR>';

/** 
 * Method 3 - array_keys() with search parameter
 */
$start = microtime(true);
$keys = array_keys($arr3,123456);
foreach($keys as $k) {
    unset($arr3[$k]);
}
echo count($arr3). 'left, in '.(microtime(true) - $start).' seconds<BR>';

The third method, array_keys() with the optional search parameter specified, seems to be by far the best method. Output example:

499999 left, in 0.090957164764404 seconds
499999left, in 0.43156313896179 seconds
499999left, in 0.028877019882202 seconds

Judging by this, the solution I would use then would be:

$keysToRemove = array_keys($items,$id);
foreach($keysToRemove as $k) {
    unset($items[$k]);
}

Password hash function for Excel VBA

Here is the MD5 code inserted in an Excel Module with the name "module_md5":

    Private Const BITS_TO_A_BYTE = 8
    Private Const BYTES_TO_A_WORD = 4
    Private Const BITS_TO_A_WORD = 32

    Private m_lOnBits(30)
    Private m_l2Power(30)

    Sub SetUpArrays()
        m_lOnBits(0) = CLng(1)
        m_lOnBits(1) = CLng(3)
        m_lOnBits(2) = CLng(7)
        m_lOnBits(3) = CLng(15)
        m_lOnBits(4) = CLng(31)
        m_lOnBits(5) = CLng(63)
        m_lOnBits(6) = CLng(127)
        m_lOnBits(7) = CLng(255)
        m_lOnBits(8) = CLng(511)
        m_lOnBits(9) = CLng(1023)
        m_lOnBits(10) = CLng(2047)
        m_lOnBits(11) = CLng(4095)
        m_lOnBits(12) = CLng(8191)
        m_lOnBits(13) = CLng(16383)
        m_lOnBits(14) = CLng(32767)
        m_lOnBits(15) = CLng(65535)
        m_lOnBits(16) = CLng(131071)
        m_lOnBits(17) = CLng(262143)
        m_lOnBits(18) = CLng(524287)
        m_lOnBits(19) = CLng(1048575)
        m_lOnBits(20) = CLng(2097151)
        m_lOnBits(21) = CLng(4194303)
        m_lOnBits(22) = CLng(8388607)
        m_lOnBits(23) = CLng(16777215)
        m_lOnBits(24) = CLng(33554431)
        m_lOnBits(25) = CLng(67108863)
        m_lOnBits(26) = CLng(134217727)
        m_lOnBits(27) = CLng(268435455)
        m_lOnBits(28) = CLng(536870911)
        m_lOnBits(29) = CLng(1073741823)
        m_lOnBits(30) = CLng(2147483647)

        m_l2Power(0) = CLng(1)
        m_l2Power(1) = CLng(2)
        m_l2Power(2) = CLng(4)
        m_l2Power(3) = CLng(8)
        m_l2Power(4) = CLng(16)
        m_l2Power(5) = CLng(32)
        m_l2Power(6) = CLng(64)
        m_l2Power(7) = CLng(128)
        m_l2Power(8) = CLng(256)
        m_l2Power(9) = CLng(512)
        m_l2Power(10) = CLng(1024)
        m_l2Power(11) = CLng(2048)
        m_l2Power(12) = CLng(4096)
        m_l2Power(13) = CLng(8192)
        m_l2Power(14) = CLng(16384)
        m_l2Power(15) = CLng(32768)
        m_l2Power(16) = CLng(65536)
        m_l2Power(17) = CLng(131072)
        m_l2Power(18) = CLng(262144)
        m_l2Power(19) = CLng(524288)
        m_l2Power(20) = CLng(1048576)
        m_l2Power(21) = CLng(2097152)
        m_l2Power(22) = CLng(4194304)
        m_l2Power(23) = CLng(8388608)
        m_l2Power(24) = CLng(16777216)
        m_l2Power(25) = CLng(33554432)
        m_l2Power(26) = CLng(67108864)
        m_l2Power(27) = CLng(134217728)
        m_l2Power(28) = CLng(268435456)
        m_l2Power(29) = CLng(536870912)
        m_l2Power(30) = CLng(1073741824)
    End Sub

    Private Function LShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            LShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And 1 Then
                LShift = &H80000000
            Else
                LShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        If (lValue And m_l2Power(31 - iShiftBits)) Then
            LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
        Else
            LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
        End If
    End Function

    Private Function RShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            RShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And &H80000000 Then
                RShift = 1
            Else
                RShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)

        If (lValue And &H80000000) Then
            RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
        End If
    End Function

    Private Function RotateLeft(lValue, iShiftBits)
        RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
    End Function

    Private Function AddUnsigned(lX, lY)
        Dim lX4
        Dim lY4
        Dim lX8
        Dim lY8
        Dim lResult

        lX8 = lX And &H80000000
        lY8 = lY And &H80000000
        lX4 = lX And &H40000000
        lY4 = lY And &H40000000

        lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)

        If lX4 And lY4 Then
            lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
        ElseIf lX4 Or lY4 Then
            If lResult And &H40000000 Then
                lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
            Else
                lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
            End If
        Else
            lResult = lResult Xor lX8 Xor lY8
        End If

        AddUnsigned = lResult
    End Function

    Private Function F(x, y, z)
        F = (x And y) Or ((Not x) And z)
    End Function

    Private Function G(x, y, z)
        G = (x And z) Or (y And (Not z))
    End Function

    Private Function H(x, y, z)
        H = (x Xor y Xor z)
    End Function

    Private Function I(x, y, z)
        I = (y Xor (x Or (Not z)))
    End Function

    Private Sub FF(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub GG(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub HH(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub II(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Function ConvertToWordArray(sMessage)
        Dim lMessageLength
        Dim lNumberOfWords
        Dim lWordArray()
        Dim lBytePosition
        Dim lByteCount
        Dim lWordCount

        Const MODULUS_BITS = 512
        Const CONGRUENT_BITS = 448

        lMessageLength = Len(sMessage)

        lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
        ReDim lWordArray(lNumberOfWords - 1)

        lBytePosition = 0
        lByteCount = 0
        Do Until lByteCount >= lMessageLength
            lWordCount = lByteCount \ BYTES_TO_A_WORD
            lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
            lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
            lByteCount = lByteCount + 1
        Loop

        lWordCount = lByteCount \ BYTES_TO_A_WORD
        lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE

        lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)

        lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
        lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)

        ConvertToWordArray = lWordArray
    End Function

    Private Function WordToHex(lValue)
        Dim lByte
        Dim lCount

        For lCount = 0 To 3
            lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
            WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
        Next
    End Function

    Public Function MD5(sMessage)

        module_md5.SetUpArrays

        Dim x
        Dim k
        Dim AA
        Dim BB
        Dim CC
        Dim DD
        Dim a
        Dim b
        Dim c
        Dim d

        Const S11 = 7
        Const S12 = 12
        Const S13 = 17
        Const S14 = 22
        Const S21 = 5
        Const S22 = 9
        Const S23 = 14
        Const S24 = 20
        Const S31 = 4
        Const S32 = 11
        Const S33 = 16
        Const S34 = 23
        Const S41 = 6
        Const S42 = 10
        Const S43 = 15
        Const S44 = 21

        x = ConvertToWordArray(sMessage)

        a = &H67452301
        b = &HEFCDAB89
        c = &H98BADCFE
        d = &H10325476

        For k = 0 To UBound(x) Step 16
            AA = a
            BB = b
            CC = c
            DD = d

            FF a, b, c, d, x(k + 0), S11, &HD76AA478
            FF d, a, b, c, x(k + 1), S12, &HE8C7B756
            FF c, d, a, b, x(k + 2), S13, &H242070DB
            FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
            FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
            FF d, a, b, c, x(k + 5), S12, &H4787C62A
            FF c, d, a, b, x(k + 6), S13, &HA8304613
            FF b, c, d, a, x(k + 7), S14, &HFD469501
            FF a, b, c, d, x(k + 8), S11, &H698098D8
            FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
            FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
            FF b, c, d, a, x(k + 11), S14, &H895CD7BE
            FF a, b, c, d, x(k + 12), S11, &H6B901122
            FF d, a, b, c, x(k + 13), S12, &HFD987193
            FF c, d, a, b, x(k + 14), S13, &HA679438E
            FF b, c, d, a, x(k + 15), S14, &H49B40821

            GG a, b, c, d, x(k + 1), S21, &HF61E2562
            GG d, a, b, c, x(k + 6), S22, &HC040B340
            GG c, d, a, b, x(k + 11), S23, &H265E5A51
            GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
            GG a, b, c, d, x(k + 5), S21, &HD62F105D
            GG d, a, b, c, x(k + 10), S22, &H2441453
            GG c, d, a, b, x(k + 15), S23, &HD8A1E681
            GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
            GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
            GG d, a, b, c, x(k + 14), S22, &HC33707D6
            GG c, d, a, b, x(k + 3), S23, &HF4D50D87
            GG b, c, d, a, x(k + 8), S24, &H455A14ED
            GG a, b, c, d, x(k + 13), S21, &HA9E3E905
            GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
            GG c, d, a, b, x(k + 7), S23, &H676F02D9
            GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A

            HH a, b, c, d, x(k + 5), S31, &HFFFA3942
            HH d, a, b, c, x(k + 8), S32, &H8771F681
            HH c, d, a, b, x(k + 11), S33, &H6D9D6122
            HH b, c, d, a, x(k + 14), S34, &HFDE5380C
            HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
            HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
            HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
            HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
            HH a, b, c, d, x(k + 13), S31, &H289B7EC6
            HH d, a, b, c, x(k + 0), S32, &HEAA127FA
            HH c, d, a, b, x(k + 3), S33, &HD4EF3085
            HH b, c, d, a, x(k + 6), S34, &H4881D05
            HH a, b, c, d, x(k + 9), S31, &HD9D4D039
            HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
            HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
            HH b, c, d, a, x(k + 2), S34, &HC4AC5665

            II a, b, c, d, x(k + 0), S41, &HF4292244
            II d, a, b, c, x(k + 7), S42, &H432AFF97
            II c, d, a, b, x(k + 14), S43, &HAB9423A7
            II b, c, d, a, x(k + 5), S44, &HFC93A039
            II a, b, c, d, x(k + 12), S41, &H655B59C3
            II d, a, b, c, x(k + 3), S42, &H8F0CCC92
            II c, d, a, b, x(k + 10), S43, &HFFEFF47D
            II b, c, d, a, x(k + 1), S44, &H85845DD1
            II a, b, c, d, x(k + 8), S41, &H6FA87E4F
            II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
            II c, d, a, b, x(k + 6), S43, &HA3014314
            II b, c, d, a, x(k + 13), S44, &H4E0811A1
            II a, b, c, d, x(k + 4), S41, &HF7537E82
            II d, a, b, c, x(k + 11), S42, &HBD3AF235
            II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
            II b, c, d, a, x(k + 9), S44, &HEB86D391

            a = AddUnsigned(a, AA)
            b = AddUnsigned(b, BB)
            c = AddUnsigned(c, CC)
            d = AddUnsigned(d, DD)
        Next

        MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
    End Function

How to insert multiple rows from array using CodeIgniter framework?

Multiple insert/ batch insert is now supported by CodeIgniter.

$data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name' ,
      'date' => 'My date'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name' ,
      'date' => 'Another date'
   )
);

$this->db->insert_batch('mytable', $data);

// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')

Float vs Decimal in ActiveRecord

In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.

  def change
    change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
    change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13
  end

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

Using number_format method in Laravel

Here's another way of doing it, add in app\Providers\AppServiceProvider.php

use Illuminate\Support\Str;

...

public function boot()
{
    // add Str::currency macro
    Str::macro('currency', function ($price)
    {
        return number_format($price, 2, '.', '\'');
    });
}

Then use Str::currency() in the blade templates or directly in the Expense model.

@foreach ($Expenses as $Expense)
    <tr>
        <td>{{{ $Expense->type }}}</td>
        <td>{{{ $Expense->narration }}}</td>
        <td>{{{ Str::currency($Expense->price) }}}</td>
        <td>{{{ $Expense->quantity }}}</td>
        <td>{{{ Str::currency($Expense->amount) }}}</td>                                                            
    </tr>
@endforeach

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Android Firebase, simply get one child object's data

Firebase listeners fire for both the initial data and any changes.

If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.

This is covered in Firebase's quickstart guide for Android. The relevant code and quote:

FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    System.out.println(snapshot.getValue());  //prints "Do you have data? You'll love Firebase."
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {        
  }
});

In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.

Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write

How do I include a Perl module that's in a different directory?

'use lib' can also take a single string value...

#!/usr/bin/perl
use lib '<relative-path>';
use <your lib>;

How to enable remote access of mysql in centos?

Bind-address XXX.XX.XX.XXX in /etc/my.cnf

comment line:

skip-networking

or

skip-external-locking

after edit hit service mysqld restart

login into mysql and hit this query:

GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%' IDENTIFIED BY 'password';

FLUSH PRIVILEGES;
quit;

add firewall rule:

iptables -I INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT

How to remove the left part of a string?

Remove prefix from a string

# ...
if line.startswith(prefix):
   return line[len(prefix):]

Split on the first occurrence of the separator via str.partition()

def findvar(filename, varname="Path", sep="=") :
    for line in open(filename):
        if line.startswith(varname + sep):
           head, sep_, tail = line.partition(sep) # instead of `str.split()`
           assert head == varname
           assert sep_ == sep
           return tail

Parse INI-like file with ConfigParser

from ConfigParser import SafeConfigParser
config = SafeConfigParser()
config.read(filename) # requires section headers to be present

path = config.get(section, 'path', raw=1) # case-insensitive, no interpolation

Other options

How to set Status Bar Style in Swift 3

Swift 3

In Info.plist add a row called "View controller-based status bar appearance" and set its value to No.

class YourViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.statusBarStyle = .lightContent //or .default
        setNeedsStatusBarAppearanceUpdate()

    }

}

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

Newer versions of PuTTYgen (mine is 0.64) are able to show the OpenSSH public key to be pasted in the linux system in the .ssh/authorized_keys file, as shown in the following image:

enter image description here

Change background colour for Visual Studio

Tools --> Options --> Environment --> Fonts and Colors

How to create a zip archive of a directory in Python?

I prepared a function by consolidating Mark Byers' solution with Reimund and Morten Zilmer's comments (relative path and including empty directories). As a best practice, with is used in ZipFile's file construction.

The function also prepares a default zip file name with the zipped directory name and '.zip' extension. Therefore, it works with only one argument: the source directory to be zipped.

import os
import zipfile

def zip_dir(path_dir, path_file_zip=''):
if not path_file_zip:
    path_file_zip = os.path.join(
        os.path.dirname(path_dir), os.path.basename(path_dir)+'.zip')
with zipfile.ZipFile(path_file_zip, 'wb', zipfile.ZIP_DEFLATED) as zip_file:
    for root, dirs, files in os.walk(path_dir):
        for file_or_dir in files + dirs:
            zip_file.write(
                os.path.join(root, file_or_dir),
                os.path.relpath(os.path.join(root, file_or_dir),
                                os.path.join(path_dir, os.path.pardir)))

AngularJS + JQuery : How to get dynamic content working in angularjs

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

Maintain aspect ratio of div but fill screen width and height in CSS?

Danield's answer is good, but it can only be used when the div fills the whole viewport, or by using a bit of calc, can be used if the width and height of the other content in the viewport is known.

However, by combining the margin-bottom trick with the method in the aforementioned answer, the problem can be reduced to just having to know the height of the other content. This is useful if you have a fixed height header, but the width of the sidebar, for example, is not known.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  margin-top: 100px; /* simulating a header */_x000D_
}_x000D_
_x000D_
main {_x000D_
  margin: 0 auto;_x000D_
  max-width: calc(200vh - 200px);_x000D_
}_x000D_
_x000D_
section {_x000D_
  padding-bottom: 50%;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
div {_x000D_
  position:absolute;_x000D_
  background-color: red;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
}
_x000D_
<main>_x000D_
  <section>_x000D_
    <div></div>_x000D_
  </section>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Here it is in a jsfiddle using scss, which makes it more obvious where the values come from.

Adding to the classpath on OSX

Normally there's no need for that. First of all

echo $CLASSPATH

If there's something in there, you probably want to check Applications -> Utilites -> Java.

How to multi-line "Replace in files..." in Notepad++

The workaround is

  1. search and replace \r\n to thisismynewlineword

(this will remove all the new lines and there should be whole one line)

  1. now perform your replacements

  2. search and replace thisismynewlineword to \r\n

(to undo the step 1)

The Completest Cocos2d-x Tutorial & Guide List

Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.

MySQL: determine which database is selected?

@mysql_result(mysql_query("SELECT DATABASE();"),0)

If no database selected, or there is no connection it returns NULL otherwise the name of the selected database.

Remove object from a list of objects in python

If you want to remove multiple object from a list. There are various ways to delete an object from a list

Try this code. a is list with all object, b is list object you want to remove.

example :

a = [1,2,3,4,5,6]
b = [2,3]

for i in b:
   if i in a:
      a.remove(i)

print(a)

the output is [1,4,5,6] I hope, it will work for you

Java: unparseable date exception

From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:

String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);

Next step is parse stringDate to Date:

Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);

Note that, parse method throws ParseException

"Prevent saving changes that require the table to be re-created" negative effects

Tools --> Options --> Designers node --> Uncheck " Prevent saving changes that require table recreation ".

PHP using Gettext inside <<<EOF string

As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:

<p>Hello</p>
<p><?= _("World"); ?></p>

How can I get the full/absolute URL (with domain) in Django?

If you're using django REST framework, you can use the reverse function from rest_framework.reverse. This has the same behavior as django.core.urlresolvers.reverse, except that it uses a request parameter to build a full URL.

from rest_framework.reverse import reverse

# returns the full url
url = reverse('view_name', args=(obj.pk,), request=request)

# returns only the relative url
url = reverse('view_name', args=(obj.pk,))

Edited to mention availability only in REST framework

Conditional Logic on Pandas DataFrame

In this specific example, where the DataFrame is only one column, you can write this elegantly as:

df['desired_output'] = df.le(2.5)

le tests whether elements are less than or equal 2.5, similarly lt for less than, gt and ge.

Why is the minidlna database not being refreshed?

In summary, the most reliable way to have MiniDLNA rescan all media files is by issuing the following set of commands:

$ sudo minidlnad -R
$ sudo service minidlna restart

Client-side script to rescan server

However, every so often MiniDLNA will be running on a server. Here is a client-side script to request a rescan on such a server:

#!/usr/bin/env bash
ssh -t server.on.lan 'sudo minidlnad -R && sudo service minidlna restart'

How can an html element fill out 100% of the remaining screen height, using css only?

CSS PLaY | cross browser fixed header/footer/centered single column layout

CSS Frames, version 2: Example 2, specified width | 456 Berea Street

One important thing is that although this sounds easy, there's going to be quite a bit of ugly code going into your CSS file to get an effect like this. Unfortunately, it really is the only option.

Why is php not running?

To answer the original question "Why is php not running?" The file your browser is asking for must have the .php extension. If the file has the .html extension, php will not be executed.

Difference between numeric, float and decimal in SQL Server

Although the question didn't include the MONEY data type some people coming across this thread might be tempted to use the MONEY data type for financial calculations.

Be wary of the MONEY data type, it's of limited precision.

There is a lot of good information about it in the answers to this Stackoverflow question:

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

Colspan all columns

For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5".

The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:

IE implements the HTML 3.2 definition, it sets colspan=0 as colspan=1.

The bug is well documented.

How do I get currency exchange rates via an API such as Google Finance?

If you need a free and simple API for converting one currency to another, try free.currencyconverterapi.com.

Disclaimer, I'm the author of the website and I use it for one of my other websites.

The service is free to use even for commercial applications but offers no warranty. For performance reasons, the values are only updated every hour.

A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=EUR_PHP&compact=ultra&apiKey=sample-api-key which will return a json-formatted value, e.g. {"EUR_PHP":60.849184}

How to format LocalDate to string?

With the help of ProgrammersBlock posts I came up with this. My needs were slightly different. I needed to take a string and return it as a LocalDate object. I was handed code that was using the older Calendar and SimpleDateFormat. I wanted to make it a little more current. This is what I came up with.

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;


    void ExampleFormatDate() {

    LocalDate formattedDate = null;  //Declare LocalDate variable to receive the formatted date.
    DateTimeFormatter dateTimeFormatter;  //Declare date formatter
    String rawDate = "2000-01-01";  //Test string that holds a date to format and parse.

    dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;

    //formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
    //First, the rawDate string is formatted according to DateTimeFormatter.  Second, that formatted string is parsed into
    //the LocalDate formattedDate object.
    formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));

}

Hopefully this will help someone, if anyone sees a better way of doing this task please add your input.

What is NODE_ENV and how to use it in Express?

Typically, you'd use the NODE_ENV variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV is set to production or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error:

app.get('/error', function(req, res) {
  if ('production' !== app.get('env')) {
    console.log("Forcing an error!");
  }
  throw new Error('TestError');
});

app.use(function (req, res, next) {
  res.status(501).send("Error!")
})

Note that the latter app.use() must be last, after all other method handlers!

If you set NODE_ENV to production before you start your server, and then send a GET /error request to it, you should not see the text Forcing an error! in the console, and the response should not contain a stack trace in the HTML body (which origins from Express). If, instead, you set NODE_ENV to something else before starting your server, the opposite should happen.

In Linux, set the environment variable NODE_ENV like this:

export NODE_ENV='value'

Java method: Finding object in array list given a known attribute value

If you have to get an attribute that is not the ID. I would use CollectionUtils.

Dog someDog = new Dog();
Dog dog = CollectionUtils(dogList, new Predicate() {

@Override
public boolean evaluate(Object o)
{
    Dog d = (Dog)o;
    return someDog.getName().equals(d.getName());
}
});

CryptographicException 'Keyset does not exist', but only through WCF

This is the only solution worked for me.

    // creates the CspParameters object and sets the key container name used to store the RSA key pair
    CspParameters cp = new CspParameters();
    cp.KeyContainerName = "MyKeyContainerName"; //Eg: Friendly name

    // instantiates the rsa instance accessing the key container MyKeyContainerName
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
    // add the below line to delete the key entry in MyKeyContainerName
    // rsa.PersistKeyInCsp = false;

    //writes out the current key pair used in the rsa instance
    Console.WriteLine("Key is : \n" + rsa.ToXmlString(true));

Reference 1

Reference 2

How to create directory automatically on SD card

Had the same problem and just want to add that AndroidManifest.xml also needs this permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

What is the relative performance difference of if/else versus switch statement in Java?

For most switch and most if-then-else blocks, I can't imagine that there are any appreciable or significant performance related concerns.

But here's the thing: if you're using a switch block, its very use suggests that you're switching on a value taken from a set of constants known at compile time. In this case, you really shouldn't be using switch statements at all if you can use an enum with constant-specific methods.

Compared to a switch statement, an enum provides better type safety and code that is easier to maintain. Enums can be designed so that if a constant is added to the set of constants, your code won't compile without providing a constant-specific method for the new value. On the other hand, forgetting to add a new case to a switch block can sometimes only be caught at run time if you're lucky enough to have set your block up to throw an exception.

Performance between switch and an enum constant-specific method should not be significantly different, but the latter is more readable, safer, and easier to maintain.

How do I remove documents using Node.js Mongoose?

Simply do

FBFriendModel.remove().exec();

How can I display a messagebox in ASP.NET?

The best solution is a minimal use of java directly in the visualstudio GUI

here it is: On a button go to the "OnClientClick" property (its not into events*) overthere type:

return confirm('are you sure?')

it will put a dialog with cancel ok buttons transparent over current page if cancel is pressed no postback will ocure. However if you want only ok button type:

alert ('i told you so')

The events like onclick work server side they execute your code, while OnClientClick runs in the browser side. the come most close to a basic dialog

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

add this line in your build.gradle

 defaultConfig {
    ............
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
    compileOptions.encoding = 'ISO-8859-1'
    multiDexEnabled true
}

What are invalid characters in XML

Another easy way to escape potentially unwanted XML / XHTML chars in C# is:

WebUtility.HtmlEncode(stringWithStrangeChars)

What's the difference between a method and a function?

Since you mentioned Python, the following might be a useful illustration of the relationship between methods and objects in most modern object-oriented languages. In a nutshell what they call a "method" is just a function that gets passed an extra argument (as other answers have pointed out), but Python makes that more explicit than most languages.

# perfectly normal function
def hello(greetee):
  print "Hello", greetee

# generalise a bit (still a function though)
def greet(greeting, greetee):
  print greeting, greetee

# hide the greeting behind a layer of abstraction (still a function!)
def greet_with_greeter(greeter, greetee):
  print greeter.greeting, greetee

# very simple class we can pass to greet_with_greeter
class Greeter(object):
  def __init__(self, greeting):
    self.greeting = greeting

  # while we're at it, here's a method that uses self.greeting...
  def greet(self, greetee):
    print self.greeting, greetee

# save an object of class Greeter for later
hello_greeter = Greeter("Hello")

# now all of the following print the same message
hello("World")
greet("Hello", "World")
greet_with_greeter(hello_greeter, "World")
hello_greeter.greet("World")

Now compare the function greet_with_greeter and the method greet: the only difference is the name of the first parameter (in the function I called it "greeter", in the method I called it "self"). So I can use the greet method in exactly the same way as I use the greet_with_greeter function (using the "dot" syntax to get at it, since I defined it inside a class):

Greeter.greet(hello_greeter, "World")

So I've effectively turned a method into a function. Can I turn a function into a method? Well, as Python lets you mess with classes after they're defined, let's try:

Greeter.greet2 = greet_with_greeter
hello_greeter.greet2("World")

Yes, the function greet_with_greeter is now also known as the method greet2. This shows the only real difference between a method and a function: when you call a method "on" an object by calling object.method(args), the language magically turns it into method(object, args).

(OO purists might argue a method is something different from a function, and if you get into advanced Python or Ruby - or Smalltalk! - you will start to see their point. Also some languages give methods special access to bits of an object. But the main conceptual difference is still the hidden extra parameter.)

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

Using the -n /usr/local/bin flag does work, BUT I had to come back to this page every time I wanted to update a package again. So I figured out a permanent fix for this.

For those interested in fixing this permanently:

Create a ~/.gemrc file

vim .gemrc

With the following content:

:gemdir:
   - ~/.gem/ruby
install: -n /usr/local/bin

Now you can run your command normally without the -n flag.

Enjoy!

Get a particular cell value from HTML table using JavaScript

You can also use the DOM way to obtain the cell value: Cells[0].firstChild.data

Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html

Fatal error: Class 'SoapClient' not found

For XAMPP users, open php.ini file located in C:/xampp/php and remove the ; from the beginning of extension=soap. Then restart Apache and that's it!

SQL Plus change current directory

I don't think you can!

/home/export/user1 $ sqlplus / 
> @script1.sql
> HOST CD /home/export/user2
> @script2.sql

script2.sql has to be in /home/export/user1.

You either use the full path, or exit the script and start sqlplus again from the right directory.

#!/bin/bash
oraenv .
cd /home/export/user1
sqlplus / @script1.sql
cd /home/export/user2
sqlplus / @script2.sql

(something like that - doing this from memory!)

'POCO' definition

"Plain Old C# Object"

Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.

EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.

TO CLARIFY: In other words, they don’t derive from some special base class, nor do they return any special types for their properties.

See below for an example of each.

Example of a POCO:

public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}

Example of something that isn’t a POCO:

public class PersonComponent : System.ComponentModel.Component
{
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public string Name { get; set; }

    public int Age { get; set; }
}

The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is not just a plain old object anymore.

How to Call Controller Actions using JQuery in ASP.NET MVC

the previous response is ASP.NET only

you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

and then a similar block of code but simpler...

$.ajax({ url: '/Controller/Action/Id',
         success: function(data) { alert(data); }, 
         statusCode : {
             404: function(content) { alert('cannot find resource'); },
             500: function(content) { alert('internal server error'); }
         }, 
         error: function(req, status, errorObj) {
               // handle status === "timeout"
               // handle other errors
         }
});

I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

MySQL skip first 10 results

LIMIT allow you to skip any number of rows. It has two parameters, and first of them - how many rows to skip

Can I load a UIImage from a URL?

You can try SDWebImage, it provides:

  1. Asynchronous loading
  2. Caching for offline use
  3. Place holder image to appear while loading
  4. Works well with UITableView

Quick example:

    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

javascript object max size limit

Step 1 is always to first determine where the problem lies. Your title and most of your question seem to suggest that you're running into quite a low length limit on the length of a string in JavaScript / on browsers, an improbably low limit. You're not. Consider:

var str;

document.getElementById('theButton').onclick = function() {
  var build, counter;

  if (!str) {
    str = "0123456789";
    build = [];
    for (counter = 0; counter < 900; ++counter) {
      build.push(str);
    }
    str = build.join("");
  }
  else {
    str += str;
  }
  display("str.length = " + str.length);
};

Live copy

Repeatedly clicking the relevant button keeps making the string longer. With Chrome, Firefox, Opera, Safari, and IE, I've had no trouble with strings more than a million characters long:

str.length = 9000
str.length = 18000
str.length = 36000
str.length = 72000
str.length = 144000
str.length = 288000
str.length = 576000
str.length = 1152000
str.length = 2304000
str.length = 4608000
str.length = 9216000
str.length = 18432000

...and I'm quite sure I could got a lot higher than that.

So it's nothing to do with a length limit in JavaScript. You haven't show your code for sending the data to the server, but most likely you're using GET which means you're running into the length limit of a GET request, because GET parameters are put in the query string. Details here.

You need to switch to using POST instead. In a POST request, the data is in the body of the request rather than in the URL, and can be very, very large indeed.

What is a "cache-friendly" code?

Welcome to the world of Data Oriented Design. The basic mantra is to Sort, Eliminate Branches, Batch, Eliminate virtual calls - all steps towards better locality.

Since you tagged the question with C++, here's the obligatory typical C++ Bullshit. Tony Albrecht's Pitfalls of Object Oriented Programming is also a great introduction into the subject.

Newline in markdown table?

When you're exporting to HTML, using <br> works. However, if you're using pandoc to export to LaTeX/PDF as well, you should use grid tables:

+---------------+---------------+--------------------+
| Fruit         | Price         | Advantages         |
+===============+===============+====================+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

In my case this was caused by an integer overflow. I had a UInt16, and was doubling the value to put into an Int. The faulty code was

let result = Int(myUInt16 * 2)

However, this multiplies as a UInt16, then converts to Int. So if myUInt16 contains a value over 32767 then an overflow occurs.

All was well once I corrected the code to

let result = Int(myUint16) * 2

Maximum number of rows of CSV data in excel sheet

CSV files have no limit of rows you can add to them. Excel won't hold more that the 1 million lines of data if you import a CSV file having more lines.

Excel will actually ask you whether you want to proceed when importing more than 1 million data rows. It suggests to import the remaining data by using the text import wizard again - you will need to set the appropriate line offset.

Eloquent ORM laravel 5 Get Array of ids

The correct answer to that is the method lists, it's very simple like this:

$test=test::select('id')->where('id' ,'>' ,0)->lists('id');

Regards!

How do you explicitly set a new property on `window` in TypeScript?

Here's how to do it, if you're using TypeScript Definition Manager!

npm install typings --global

Create typings/custom/window.d.ts:

interface Window {
  MyNamespace: any;
}

declare var window: Window;

Install your custom typing:

typings install file:typings/custom/window.d.ts --save --global

Done, use it‌! Typescript won't complain anymore:

window.MyNamespace = window.MyNamespace || {};

IF EXISTS condition not working with PLSQL

Unfortunately PL/SQL doesn't have IF EXISTS operator like SQL Server. But you can do something like this:

begin
  for x in ( select count(*) cnt
               from dual 
              where exists (
                select 1 from courseoffering co
                  join co_enrolment ce on ce.co_id = co.co_id
                 where ce.s_regno = 403 
                   and ce.coe_completionstatus = 'C' 
                   and co.c_id = 803 ) )
  loop
        if ( x.cnt = 1 ) 
        then
           dbms_output.put_line('exists');
        else 
           dbms_output.put_line('does not exist');
        end if;
  end loop;
end;
/

Windows Scipy Install: No Lapack/Blas Resources Found

You probably just have too new (unsupported) Python 3.x installed.

This page has overcomplicated solutions to the problem. Most of numpy / scipy users should not need to compile their numpy installations or need to rely on 3rd party "numpy+mkl" wheels.

Downloading a compiler is an anti-pattern, you do not want to build numpy, only use it. [github.com/numpy]

Solution

  • Once you have installed supported python version, remove your non-working numpy installation with
pip uninstall numpy

and install scipy with

pip install scipy --only-binary numpy
  • The --only-binary numpy will force installing binary wheel (.whl) version of numpy. If it fails, you have too new (not yet supported) version of python.

  • If you have multiple python versions installed, you can ensure that pip is installing the python version you want by

<path_to_python_executable> -m pip install <X> 

instead of pip install <X>.

Why this is happening?

  • Scipy relies on numpy, as can be seen from the setup.py or just by reading the pip install logs.
  • If you have too new (non-supported) python installation, there are no built wheel (.whl) in the pip repository, but tarballs (.tar.gz), which in this case require the user machine to compile some C++-code during installation. See also: Python packaging: wheels vs tarball (tar.gz)

Appendix

  • Check the https://pypi.org/project/numpy/ for list of supported Python versions. Currently (2020-11-04) the newest supported python version is Python 3.9. when using numpy 1.19.3 or above, and Python 3.8 for numpy 1.19.2. (For compatibility of older numpy versions, see numpy release notes)
  • If you are on Windows and see pip trying to install numpy-<x>.tag.gz, you know it probably will not work. Try older version of Python, instead. You want to see pip to installing a binary wheel for numpy for Windows (numpy-<x>.whl). You can check the wheels in pip available for numpy here.

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

How to "grep" out specific line ranges of a file

Put this in a file and make it executable:

#!/bin/bash
start=`grep -n $1 < $3 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[0]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo "couldn't find start pattern!" 1>&2
    exit 1
fi
stop=`tail -n +$start < $3 | grep -n $2 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[1]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo "couldn't find end pattern!" 1>&2
    exit 1
fi

stop=$(( $stop + $start - 1))

sed "$start,$stop!d" < $3

Execute the file with arguments (NOTE that the script does not handle spaces in arguments!):

  1. Starting grep pattern
  2. Stopping grep pattern
  3. File path

To use with your example, use arguments: 1234 5555 myfile.txt

Includes lines with starting and stopping pattern.

Do I need to explicitly call the base virtual destructor?

No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.

Difference between HttpModule and HttpClientModule

There is a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

A reason for existing

When you use HttpClient with Observable, you have to use .subscribe(x=>...) in the rest of your code.

This is because Observable<HttpResponse<T>> is tied to HttpResponse.

This tightly couples the http layer with the rest of your code.

This library encapsulates the .subscribe(x => ...) part and exposes only the data and error through your Models.

With strongly-typed callbacks, you only have to deal with your Models in the rest of your code.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the getRaceInfo API called as shown below.

  ngOnInit() {    
    this.service.getRaceInfo(response => this.result = response.result,
                                error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Also, you can still use the traditional route and return Observable<HttpResponse<T>> from Service API.

server error:405 - HTTP verb used to access this page is not allowed

I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).

Take n rows from a spark dataframe and pass to toPandas()

You can use the limit(n) function:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()

Or:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()

ASP.NET MVC Dropdown List From SelectList

You are missing setting what field is the Text and Value in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text", 1);

BTW, you can use a list of array of any type... and then just set the name of the properties that will act as Text and Value.

I think it is better to do it like this:

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text");

I removed the -1 item, and the setting of each items selected true/false.

Then, in your view:

@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")

This way, if you set the "Select one" item, and you don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).

If you need to set one of the SelectList items as selected, you can use:

u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);

How to get Javascript Select box's selected text

Just use

$('#SelectBoxId option:selected').text(); For Getting text as listed

$('#SelectBoxId').val(); For Getting selected Index value

Combine Points with lines with ggplot2

The following example using the iris dataset works fine:

dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
      id.vars = "Species")
ggplot(aes(x = 1:nrow(iris), y = value, color = variable), data = dat) +  
      geom_point() + geom_line()

enter image description here

Setting action for back button in navigation controller

onegray's solution is not safe.According to the official documents by Apple,https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html, we should avoid doing that.

"If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime. This is less likely to be an issue if you’re using categories with your own classes, but can cause problems when using categories to add methods to standard Cocoa or Cocoa Touch classes."

How to subtract 30 days from the current date using SQL Server

You can convert it to datetime, and then use DATEADD(DAY, -30, date).

See here.

edit

I suspect many people are finding this question because they want to substract from current date (as is the title of the question, but not what OP intended). The comment of munyul below answers that question more specifically. Since comments are considered ethereal (may be deleted at any given point), I'll repeat it here:

DATEADD(DAY, -30, GETDATE())

assign value using linq

You can create a extension method:

public static IEnumerable<T> Do<T>(this IEnumerable<T> self, Action<T> action) {
    foreach(var item in self) {
        action(item);
        yield return item;
    }
}

And then use it in code:

listofCompany.Do(d=>d.Id = 1);
listofCompany.Where(d=>d.Name.Contains("Inc")).Do(d=>d.Id = 1);

IllegalMonitorStateException on wait() call

Not sure if this will help somebody else out or not but this was the key part to fix my problem in user "Tom Hawtin - tacklin"'s answer above:

synchronized (lock) {
    makeWakeupNeeded();
    lock.notifyAll();
}

Just the fact that the "lock" is passed as an argument in synchronized() and it is also used in "lock".notifyAll();

Once I made it in those 2 places I got it working

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

This error happened to me in a Grails Application with the JTDS Driver 1.3.0 (SQL Server). The problem was an incorrect login in SQL Server. After solve this issue (in SQL Server) my app was correctly deployed in Tomcat. Tip: I saw the error in stacktrace.log

jQuery if Element has an ID?

You can do

document.getElementById(id) or 
$(id).length > 0

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

OpenSSL: unable to verify the first certificate for Experian URL

Adding additional information to emboss's answer.

To put it simply, there is an incorrect cert in your certificate chain.

For example, your certificate authority will have most likely given you 3 files.

  • your_domain_name.crt
  • DigiCertCA.crt # (Or whatever the name of your certificate authority is)
  • TrustedRoot.crt

You most likely combined all of these files into one bundle.

-----BEGIN CERTIFICATE----- 
(Your Primary SSL certificate: your_domain_name.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Intermediate certificate: DigiCertCA.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Root certificate: TrustedRoot.crt) 
-----END CERTIFICATE-----

If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.

Redownload all certs from your certificate authority and make a fresh bundle.

android asynctask sending callbacks to ui

I felt the below approach is very easy.

I have declared an interface for callback

public interface AsyncResponse {
    void processFinish(Object output);
}

Then created asynchronous Task for responding all type of parallel requests

 public class MyAsyncTask extends AsyncTask<Object, Object, Object> {

    public AsyncResponse delegate = null;//Call back interface

    public MyAsyncTask(AsyncResponse asyncResponse) {
        delegate = asyncResponse;//Assigning call back interfacethrough constructor
    }

    @Override
    protected Object doInBackground(Object... params) {

    //My Background tasks are written here

      return {resutl Object}

    }

    @Override
    protected void onPostExecute(Object result) {
        delegate.processFinish(result);
    }

}

Then Called the asynchronous task when clicking a button in activity Class.

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        Button mbtnPress = (Button) findViewById(R.id.btnPress);

        mbtnPress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {

                    @Override
                    public void processFinish(Object output) {
                        Log.d("Response From Asynchronous task:", (String) output);          
                        mbtnPress.setText((String) output);
                    }
                });
                asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });

            }
        });
    }
}

Thanks

How much faster is C++ than C#?

As usual, it depends on the application. There are cases where C# is probably negligibly slower, and other cases where C++ is 5 or 10 times faster, especially in cases where operations can be easily SIMD'd.

Can I make dynamic styles in React Native?

If you are using a screen with filters for example, and you want to set the background of the filter regarding if it was selected or not, you can do:

<TouchableOpacity style={this.props.venueFilters.includes('Bar')?styles.filterBtnActive:styles.filterBtn} onPress={()=>this.setFilter('Bar')}>
<Text numberOfLines={1}>
Bar
</Text>
</TouchableOpacity>

On which set filter is:

setVenueFilter(filter){
  var filters = this.props.venueFilters;
  filters.push(filter);
  console.log(filters.includes('Bar'), "Inclui Bar");
  this.setState(previousState => {
    return { updateFilter: !previousState.updateFilter };
  });
  this.props.setVenueFilter(filters);
}

PS: the function this.props.setVenueFilter(filters) is a redux action, and this.props.venueFilters is a redux state.

How to use UIScrollView in Storyboard

Getting Scrolling to work in iOS7 and Auto-layout in iOS 7 and XCode 5.

In addition to this: https://stackoverflow.com/a/22489795/1553014

Apparently, all we need to do is:

  1. Set all constraints to Scroll View (i.e. fix scroll view first)

  2. Then set distance-from-scrollView constraint to the bottom most item to scroll view (which is the super view).

Note: Step 2 will tell storyboard where the last piece of content lies within Scroll view.

Seeding the random number generator in Javascript

Please see Pierre L'Ecuyer's work going back to the late 1980s and early 1990s. There are others as well. Creating a (pseudo) random number generator on your own, if you are not an expert, is pretty dangerous, because there is a high likelihood of either the results not being statistically random or in having a small period. Pierre (and others) have put together some good (pseudo) random number generators that are easy to implement. I use one of his LFSR generators.

https://www.iro.umontreal.ca/~lecuyer/myftp/papers/handstat.pdf

Phil Troy

How to split a list by comma not space

I think the canonical method is:

while IFS=, read field1 field2 field3 field4 field5 field6; do 
  do stuff
done < CSV.file

If you don't know or don't care about how many fields there are:

IFS=,
while read line; do
  # split into an array
  field=( $line )
  for word in "${field[@]}"; do echo "$word"; done

  # or use the positional parameters
  set -- $line
  for word in "$@"; do echo "$word"; done

done < CSV.file

How to select an element by classname using jqLite?

If elem.find() is not working for you, check that you are including JQuery script before angular script....

Application Crashes With "Internal Error In The .NET Runtime"

I never figured out why this was happening for me. It was consistently reproducible for one of my applications, but went away after simply rebooting.

I am running Windows 2004 Build 19582.1001 (Insider Preview) with .net-4.8 and I also would not be surprised if this were due to something like a hardware memory error. Also, my application does load some unmanaged code and initialize it, so I can’t prove that the crash didn’t come from that.

Java java.sql.SQLException: Invalid column index on preparing statement

In date '?', the '?' is a literal string with value ?, not a parameter placeholder, so your query does not have any parameters. The date is a shorthand cast from (literal) string to date. You need to replace date '?' with ? to actually have a parameter.

Also if you know it is a date, then use setDate(..) and not setString(..) to set the parameter.

No Title Bar Android Theme

In your styles.xml, modify style "AppTheme" like

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item> 
    </style>

Laravel PHP Command Not Found

If you're using Ubuntu 16.04.

  1. You need to find the composer config files in my case is :
    ~/.config/composer or in other cases ~/.composer/
    you can see the dir after this command
    composer global require "laravel/installer"

  2. after Laravel Installed you can find your laravel in ~/.config/composer/vendor/laravel/installer/.
    and you will find the Laravel shortcut command in here :
    ~/.config/composer/vendor/bin/

  3. set your .bashrc using nano ~/.bashrc and export your composer config file :

    export PATH="$PATH:$HOME/.config/composer/vendor/bin"

    or you can use allias. but above solution is recommended.

    alias laravel='~/.config/composer/vendor/laravel/installer/laravel'

  4. Now refresh your bashrc using source ~/.bashrc and then laravel is ready!!

above steps works with me in Ubuntu 16.04

"Find next" in Vim

It is n for next and N for previous.

And if you use reverse search with ? (for example, ?cake) instead of /, it is the other way round.

If it is installed on your system, you should try to run vimtutor command from your terminal, which will start a tutorial of the basic Vim commands.

Rob Wells advice about * and # is also very pertinent.

Why do multiple-table joins produce duplicate rows?

If one of the tables M, S, D, or H has more than one row for a given Id (if just the Id column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).

References:

Related Question on MSDN Forum

$http.get(...).success is not a function

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (response){

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

Difference between int and double

int and double have different semantics. Consider division. 1/2 is 0, 1.0/2.0 is 0.5. In any given situation, one of those answers will be right and the other wrong.

That said, there are programming languages, such as JavaScript, in which 64-bit float is the only numeric data type. You have to explicitly truncate some division results to get the same semantics as Java int. Languages such as Java that support integer types make truncation automatic for integer variables.

In addition to having different semantics from double, int arithmetic is generally faster, and the smaller size (32 bits vs. 64 bits) leads to more efficient use of caches and data transfer bandwidth.

Is the practice of returning a C++ reference variable evil?

It's not evil. Like many things in C++, it's good if used correctly, but there are many pitfalls you should be aware of when using it (like returning a reference to a local variable).

There are good things that can be achieved with it (like map[name] = "hello world")

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

How Can I Truncate A String In jQuery?

  function truncateString(str, length) {
     return str.length > length ? str.substring(0, length - 3) + '...' : str
  }

Calculate number of hours between 2 dates in PHP

Unfortunately the solution provided by FaileN doesn't work as stated by Walter Tross.. days may not be 24 hours!

I like to use the PHP Objects where possible and for a bit more flexibility I have come up with the following function:

/**
 * @param DateTimeInterface $a
 * @param DateTimeInterface $b
 * @param bool              $absolute Should the interval be forced to be positive?
 * @param string            $cap The greatest time unit to allow
 *
 * @return DateInterval The difference as a time only interval
 */
function time_diff(DateTimeInterface $a, DateTimeInterface $b, $absolute=false, $cap='H'){

  // Get unix timestamps, note getTimeStamp() is limited
  $b_raw = intval($b->format("U"));
  $a_raw = intval($a->format("U"));

  // Initial Interval properties
  $h = 0;
  $m = 0;
  $invert = 0;

  // Is interval negative?
  if(!$absolute && $b_raw<$a_raw){
    $invert = 1;
  }

  // Working diff, reduced as larger time units are calculated
  $working = abs($b_raw-$a_raw);

  // If capped at hours, calc and remove hours, cap at minutes
  if($cap == 'H') {
    $h = intval($working/3600);
    $working -= $h * 3600;
    $cap = 'M';
  }

  // If capped at minutes, calc and remove minutes
  if($cap == 'M') {
    $m = intval($working/60);
    $working -= $m * 60;
  }

  // Seconds remain
  $s = $working;

  // Build interval and invert if necessary
  $interval = new DateInterval('PT'.$h.'H'.$m.'M'.$s.'S');
  $interval->invert=$invert;

  return $interval;
}

This like date_diff() creates a DateTimeInterval, but with the highest unit as hours rather than years.. it can be formatted as usual.

$interval = time_diff($date_a, $date_b);
echo $interval->format('%r%H'); // For hours (with sign)

N.B. I have used format('U') instead of getTimestamp() because of the comment in the manual. Also note that 64-bit is required for post-epoch and pre-negative-epoch dates!

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

OK! I'm really sorry to those that have actually submitted comments and answers, but I found the problem. I don't think this will help a lot of others trying to track down their personal SIGSEGV, but mine (and it was very hard) was entirely related to this:

https://code.google.com/p/android/issues/detail?id=8709

The libcrypto.so in my dump kind of clued me in. I do a MD5 hash of packet data when trying to determine if I've already seen the packet, and skipping it if I had. I thought at one point this was an ugly threading issue related to tracking those hashes, but it turned out it was the java.security.MessageDigest class! It's not thread safe!

I swapped it out with a UID I was stuffing in every packet based on the device UUID and a timestamp. No problems since.

I guess the lesson I can impart to those that were in my situation is, even if you're a 100% Java application, pay attention to the native library and symbol noted in the crash dump for clues. Googling for SIGSEGV + the lib .so name will go a lot farther than the useless code=1, etc... Next think about where your Java app could touch native code, even if it's nothing you're doing. I made the mistake of assuming it was a Service + UI threading issue where the Canvas was drawing something that was null, (the most common case I Googled on SIGSEGV) and ignored the possibility it could have been completely related to code I wrote that was related to the lib .so in the crash dump. Naturally java.security would use a native component in libcrypto.so for speed, so once I clued in, I Googled for Android + SIGSEGV + libcrypto.so and found the documented issue. Good luck!

How to generate XML from an Excel VBA macro?

Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)

Script:

Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
    Dim Q As String
    Q = Chr$(34)

    Dim sXML As String

    sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
    sXML = sXML & "<rows>"


    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1
    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend

    Dim iRow As Integer
    iRow = iDataStartRow

    While Cells(iRow, 1) > ""
        sXML = sXML & "<row id=" & Q & iRow & Q & ">"

        For icol = 1 To iColCount - 1
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
           sXML = sXML & Trim$(Cells(iRow, icol))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
        Next

        sXML = sXML & "</row>"
        iRow = iRow + 1
    Wend
    sXML = sXML & "</rows>"

    Dim nDestFile As Integer, sText As String

    ''Close any open text files
    Close

    ''Get the number of the next free text file
    nDestFile = FreeFile

    ''Write the entire file to sText
    Open sOutputFileName For Output As #nDestFile
    Print #nDestFile, sXML
    Close
End Sub

Sub test()
    MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub

How do I clear all variables in the middle of a Python script?

from IPython import get_ipython;   
get_ipython().magic('reset -sf')

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

Getting visitors country from their IP

Try this simple PHP function.

<?php

function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
    $output = NULL;
    if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
        $ip = $_SERVER["REMOTE_ADDR"];
        if ($deep_detect) {
            if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
                $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
    }
    $purpose    = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
    $support    = array("country", "countrycode", "state", "region", "city", "location", "address");
    $continents = array(
        "AF" => "Africa",
        "AN" => "Antarctica",
        "AS" => "Asia",
        "EU" => "Europe",
        "OC" => "Australia (Oceania)",
        "NA" => "North America",
        "SA" => "South America"
    );
    if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
        $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
        if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
            switch ($purpose) {
                case "location":
                    $output = array(
                        "city"           => @$ipdat->geoplugin_city,
                        "state"          => @$ipdat->geoplugin_regionName,
                        "country"        => @$ipdat->geoplugin_countryName,
                        "country_code"   => @$ipdat->geoplugin_countryCode,
                        "continent"      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
                        "continent_code" => @$ipdat->geoplugin_continentCode
                    );
                    break;
                case "address":
                    $address = array($ipdat->geoplugin_countryName);
                    if (@strlen($ipdat->geoplugin_regionName) >= 1)
                        $address[] = $ipdat->geoplugin_regionName;
                    if (@strlen($ipdat->geoplugin_city) >= 1)
                        $address[] = $ipdat->geoplugin_city;
                    $output = implode(", ", array_reverse($address));
                    break;
                case "city":
                    $output = @$ipdat->geoplugin_city;
                    break;
                case "state":
                    $output = @$ipdat->geoplugin_regionName;
                    break;
                case "region":
                    $output = @$ipdat->geoplugin_regionName;
                    break;
                case "country":
                    $output = @$ipdat->geoplugin_countryName;
                    break;
                case "countrycode":
                    $output = @$ipdat->geoplugin_countryCode;
                    break;
            }
        }
    }
    return $output;
}

?>

How to use:

Example1: Get visitor IP address details

<?php

echo ip_info("Visitor", "Country"); // India
echo ip_info("Visitor", "Country Code"); // IN
echo ip_info("Visitor", "State"); // Andhra Pradesh
echo ip_info("Visitor", "City"); // Proddatur
echo ip_info("Visitor", "Address"); // Proddatur, Andhra Pradesh, India

print_r(ip_info("Visitor", "Location")); // Array ( [city] => Proddatur [state] => Andhra Pradesh [country] => India [country_code] => IN [continent] => Asia [continent_code] => AS )

?>

Example 2: Get details of any IP address. [Support IPV4 & IPV6]

<?php

echo ip_info("173.252.110.27", "Country"); // United States
echo ip_info("173.252.110.27", "Country Code"); // US
echo ip_info("173.252.110.27", "State"); // California
echo ip_info("173.252.110.27", "City"); // Menlo Park
echo ip_info("173.252.110.27", "Address"); // Menlo Park, California, United States

print_r(ip_info("173.252.110.27", "Location")); // Array ( [city] => Menlo Park [state] => California [country] => United States [country_code] => US [continent] => North America [continent_code] => NA )

?>

How to get a product's image in Magento?

First You need to verify the base, small and thumbnail image are selected in Magento admin.

admin->catalog->manage product->product->image

Then select your image roles(base,small,thumbnail)enter image description here

Then you call the image using

echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(163, 100);

Hope this helps you.

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

I was initially running:

sudo scp

Once I ran just scp, without sudo, it copied everything fine:

scp

It seems to me that sudo scp command wasn't reading my current user's SSH public key at ~/.ssh/id_rsa.pub.

How to convert a char array to a string?

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

Why does my Eclipse keep not responding?

for me, it was because of all the outgoing files, i.e workspace is not in sync with SVN, due to the 'target' folders (maven project, or when building web project), add them to svn:ignore.

Calculate AUC in R?

As mentioned by others, you can compute the AUC using the ROCR package. With the ROCR package you can also plot the ROC curve, lift curve and other model selection measures.

You can compute the AUC directly without using any package by using the fact that the AUC is equal to the probability that a true positive is scored greater than a true negative.

For example, if pos.scores is a vector containing a score of the positive examples, and neg.scores is a vector containing the negative examples then the AUC is approximated by:

> mean(sample(pos.scores,1000,replace=T) > sample(neg.scores,1000,replace=T))
[1] 0.7261

will give an approximation of the AUC. You can also estimate the variance of the AUC by bootstrapping:

> aucs = replicate(1000,mean(sample(pos.scores,1000,replace=T) > sample(neg.scores,1000,replace=T)))

Responsive web design is working on desktop but not on mobile device

Responsive meta tag

To ensure proper rendering and touch zooming for all devices, add the responsive viewport meta tag to your <head>.

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

django - get() returned more than one topic

get() returned more than one topic -- it returned 2!

The above error indicatess that you have more than one record in the DB related to the specific parameter you passed while querying using get() such as

Model.objects.get(field_name=some_param)

To avoid this kind of error in the future, you always need to do query as per your schema design. In your case you designed a table with a many-to-many relationship so obviously there will be multiple records for that field and that is the reason you are getting the above error.

So instead of using get() you should use filter() which will return multiple records. Such as

Model.objects.filter(field_name=some_param)

Please read about how to make queries in django here.

React.js, wait for setState to finish before triggering a function?

According to the docs of setState() the new state might not get reflected in the callback function findRoutes(). Here is the extract from React docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

So here is what I propose you should do. You should pass the new states input in the callback function findRoutes().

handleFormSubmit: function(input){
    // Form Input
    this.setState({
        originId: input.originId,
        destinationId: input.destinationId,
        radius: input.radius,
        search: input.search
    });
    this.findRoutes(input);    // Pass the input here
}

The findRoutes() function should be defined like this:

findRoutes: function(me = this.state) {    // This will accept the input if passed otherwise use this.state
    if (!me.originId || !me.destinationId) {
        alert("findRoutes!");
        return;
    }
    var p1 = new Promise(function(resolve, reject) {
        directionsService.route({
            origin: {'placeId': me.originId},
            destination: {'placeId': me.destinationId},
            travelMode: me.travelMode
        }, function(response, status){
            if (status === google.maps.DirectionsStatus.OK) {
                // me.response = response;
                directionsDisplay.setDirections(response);
                resolve(response);
            } else {
                window.alert('Directions config failed due to ' + status);
            }
        });
    });
    return p1
}

Django - what is the difference between render(), render_to_response() and direct_to_template()?

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render

render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])

render() is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext that I will most definitely be using from now on.


2020 EDIT: It should be noted that render_to_response() was removed in Django 3.0

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response

render_to_response(template[, dictionary][, context_instance][, mimetype])¶

render_to_response is your standard render function used in the tutorials and such. To use RequestContext you'd have to specify context_instance=RequestContext(request)


https://docs.djangoproject.com/en/1.8/ref/generic-views/#django-views-generic-simple-direct-to-template

direct_to_template is a generic view that I use in my views (as opposed to in my urls) because like the new render() function, it automatically uses RequestContext and all its context_processors.

But direct_to_template should be avoided as function based generic views are deprecated. Either use render or an actual class, see https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/

I'm happy I haven't typed RequestContext in a long, long time.

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

Kotlin DSL: add to your build.gradle.kts

tasks.withType<Test> {
        useJUnitPlatform()
}

Gradle DSL: add to your build.gradle

test {
    useJUnitPlatform()
}

What is IllegalStateException?

Usually, IllegalStateException is used to indicate that "a method has been invoked at an illegal or inappropriate time." However, this doesn't look like a particularly typical use of it.

The code you've linked to shows that it can be thrown within that code at line 259 - but only after dumping a SQLException to standard output.

We can't tell what's wrong just from that exception - and better code would have used the original SQLException as a "cause" exception (or just let the original exception propagate up the stack) - but you should be able to see more details on standard output. Look at that information, and you should be able to see what caused the exception, and fix it.

Check whether an array is empty

PHP's built-in empty() function checks to see whether the variable is empty, null, false, or a representation of zero. It doesn't return true just because the value associated with an array entry is false, in this case the array has actual elements in it and that's all that's evaluated.

If you'd like to check whether a particular error condition is set to true in an associative array, you can use the array_keys() function to filter the keys that have their value set to true.

$set_errors = array_keys( $errors, true );

You can then use the empty() function to check whether this array is empty, simultaneously telling you whether there are errors and also which errors have occurred.

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

I had the same problem as you though I have followed a different guide: http://www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/

The strange part is that, in this guide I have used, I should not have any problem with compatibility between versions (1.x against 2.x) because following the guide you use the jersey 1.8.x on pom.xmland in the web.xmlyou refer to a class (com.sun.jersey.spi.container.servlet.ServletContainer) as said before of 1.x version. So as I can infer this should be working.

My guess is because I'm using JDK 1.7 this class does not exist anymore.


After, I tried to resolve with the answers before mine, did not helped, I have made changes on the pom.xmland on the web.xml the error changed to: java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer

Which supposedly should be exist!

As result of this error, I found a "new" solution: http://marek.potociar.net/2013/06/13/jax-rs-2-0-and-jersey-2-0-released/

With Maven (archetypes), generate a jersey project, likes this:

mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.0

And it worked for me! :)

Order by in Inner Join

Avoid SELECT * in your main query.

Avoid duplicate columns: the JOIN condition ensures One.One_Name and two.One_Name will be equal therefore you don't need to return both in the SELECT clause.

Avoid duplicate column names: rename One.ID and Two.ID using 'aliases'.

Add an ORDER BY clause using the column names ('alises' where applicable) from the SELECT clause.

Suggested re-write:

SELECT T1.ID AS One_ID, T1.One_Name, 
       T2.ID AS Two_ID, T2.Two_name
  FROM One AS T1
       INNER JOIN two AS T2
          ON T1.One_Name = T2.One_Name
 ORDER 
    BY One_ID;

How can I use an ES6 import in Node.js?

You can also use npm package called esm which allows you to use ES6 modules in Node.js. It needs no configuration. With esm you will be able to use export/import in your JavaScript files.

Run the following command on your terminal

yarn add esm

or

npm install esm

After that, you need to require this package when starting your server with node. For example if your node server runs index.js file, you would use the command

node -r esm index.js

You can also add it in your package.json file like this

{
  "name": "My-app",
  "version": "1.0.0",
  "description": "Some Hack",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node -r esm index.js"
  },

}

Then run this command from the terminal to start your node server

npm start

Check this link for more details.

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

How to get the full path of running process?

I guess you already have the process object of the running process (e.g. by GetProcessesByName()). You can then get the executable file name by using

Process p;
string filename = p.MainModule.FileName;

Maximum length for MD5 input/output

MD5 processes an arbitrary-length message into a fixed-length output of 128 bits, typically represented as a sequence of 32 hexadecimal digits.