Programs & Examples On #Habari

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had the same problem, you have to load first the Moment.js file!

_x000D_
_x000D_
<script src="path/moment.js"></script>_x000D_
<script src="path/bootstrap-datetimepicker.js"></script>
_x000D_
_x000D_
_x000D_

Convert XML to JSON (and back) using Javascript

Disclaimer: I've written fast-xml-parser

Fast XML Parser can help to convert XML to JSON and vice versa. Here is the example;

var options = {
    attributeNamePrefix : "@_",
    attrNodeName: "attr", //default is 'false'
    textNodeName : "#text",
    ignoreAttributes : true,
    ignoreNameSpace : false,
    allowBooleanAttributes : false,
    parseNodeValue : true,
    parseAttributeValue : false,
    trimValues: true,
    decodeHTMLchar: false,
    cdataTagName: "__cdata", //default is 'false'
    cdataPositionChar: "\\c",
};
if(parser.validate(xmlData)=== true){//optional
    var jsonObj = parser.parse(xmlData,options);
}

If you want to parse JSON or JS object into XML then

//default options need not to set
var defaultOptions = {
    attributeNamePrefix : "@_",
    attrNodeName: "@", //default is false
    textNodeName : "#text",
    ignoreAttributes : true,
    encodeHTMLchar: false,
    cdataTagName: "__cdata", //default is false
    cdataPositionChar: "\\c",
    format: false, 
    indentBy: "  ",
    supressEmptyNode: false
};
var parser = new parser.j2xParser(defaultOptions);
var xml = parser.parse(json_or_js_obj);

Ruby Arrays: select(), collect(), and map()

When dealing with a hash {}, use both the key and value to the block inside the ||.

details.map {|key,item|"" == item}

=>[false, false, true, false, false]

AngularJS - $http.post send data as json

Use JSON.stringify() to wrap your json

var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
    $http.post(url, parameter).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        console.log(data);
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });

How to get a cookie from an AJAX response?

The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!

For this to work you need to:

1) login with the ajax request from which you expect cookies to be returned:

$.ajax("https://example.com/v2/login", {
     method: 'POST',
     data: {login_id: user, password: password},
     crossDomain: true,
     success: login_success,
     error: login_error
  });

2) Connect with xhrFields: { withCredentials: true } in the next ajax request(s) to use the credentials saved by the browser

$.ajax("https://example.com/v2/whatever", {
     method: 'GET',
     xhrFields: { withCredentials: true },
     crossDomain: true,
     success: whatever_success,
     error: whatever_error
  });

The browser takes care of these cookies for you even though they are not readable from the headers nor the document.cookie

Get HTML source of WebElement in Selenium WebDriver using Python

Using the attribute method is, in fact, easier and more straightforward.

Using Ruby with the Selenium and PageObject gems, to get the class associated with a certain element, the line would be element.attribute(Class).

The same concept applies if you wanted to get other attributes tied to the element. For example, if I wanted the string of an element, element.attribute(String).

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824

Compare two MySQL databases

I think Navicat for MySQL will be helpful for this case. It supports Data and Structure Synchronization for MySQL. enter image description here

How to send image to PHP file using Ajax?

Here is code that will upload multiple images at once, into a specific folder!

The HTML:

<form method="post" enctype="multipart/form-data" id="image_upload_form" action="submit_image.php">
<input type="file" name="images" id="images" multiple accept="image/x-png, image/gif, image/jpeg, image/jpg" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">

</ul>

The PHP:

<?php
$errors = $_FILES["images"]["error"];
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
    $name = $_FILES["images"]["name"][$key];
    //$ext = pathinfo($name, PATHINFO_EXTENSION);
    $name = explode("_", $name);
    $imagename='';
    foreach($name as $letter){
        $imagename .= $letter;
    }

    move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" .  $imagename);

}
}


echo "<h2>Successfully Uploaded Images</h2>";

And finally, the JavaSCript/Ajax:

(function () {
var input = document.getElementById("images"), 
    formdata = false;

function showUploadedItem (source) {
    var list = document.getElementById("image-list"),
        li   = document.createElement("li"),
        img  = document.createElement("img");
    img.src = source;
    li.appendChild(img);
    list.appendChild(li);
}   

if (window.FormData) {
    formdata = new FormData();
    document.getElementById("btn").style.display = "none";
}

input.addEventListener("change", function (evt) {
    document.getElementById("response").innerHTML = "Uploading . . ."
    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];

        if (!!file.type.match(/image.*/)) {
            if ( window.FileReader ) {
                reader = new FileReader();
                reader.onloadend = function (e) { 
                    showUploadedItem(e.target.result, file.fileName);
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("images[]", file);
            }
        }   
    }

    if (formdata) {
        $.ajax({
            url: "submit_image.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                document.getElementById("response").innerHTML = res;
            }
        });
    }
}, false);
}());

Hope this helps

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Another simple solution (not very elegant, but not too ugly also) is to place a inner div / span then get his height ($(this).find('span).height()).

Here is an example of using this strategy:

_x000D_
_x000D_
$(".more").click(function(){_x000D_
if($(this).parent().find('.showMore').length) {_x000D_
$(this).parent().find('.showMore').removeClass('showMore').css('max-height','90px');_x000D_
$(this).parent().find('.more').removeClass('less').text('More');_x000D_
} else {_x000D_
$(this).parent().find('.text').addClass('showMore').css('max-height',$(this).parent().find('span').height());_x000D_
$(this).parent().find('.more').addClass('less').text('Less');_x000D_
}_x000D_
});
_x000D_
* {transition: all 0.5s;}_x000D_
.text {position:relative;width:400px;max-height:90px;overflow:hidden;}_x000D_
.showMore {}_x000D_
.text::after {_x000D_
  content: "";_x000D_
    position: absolute; bottom: 0; left: 0;_x000D_
        box-shadow: inset 0 -26px 22px -17px #fff;_x000D_
    height: 39px;_x000D_
  z-index:99999;_x000D_
  width:100%;_x000D_
  opacity:1;_x000D_
}_x000D_
.showMore::after {opacity:0;}_x000D_
.more {border-top:1px solid gray;width:400px;color:blue;cursor:pointer;}_x000D_
.more.less {border-color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<div class="text">_x000D_
<span>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</span></div>_x000D_
<div class="more">More</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(This specific example is using this trick to animate the max-height and avoiding animation delay when collapsing (when using high number for the max-height property).

How to load json into my angular.js ng-model?

Here's a simple example of how to load JSON data into an Angular model.

I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.

http://www.iNorthwind.com/Service1.svc/getAllCustomers

It returns some JSON data which looks like this:

{ 
    "GetAllCustomersResult" : 
        [
            {
              "CompanyName": "Alfreds Futterkiste",
              "CustomerID": "ALFKI"
            },
            {
              "CompanyName": "Ana Trujillo Emparedados y helados",
              "CustomerID": "ANATR"
            },
            {
              "CompanyName": "Antonio Moreno Taquería",
              "CustomerID": "ANTON"
            }
        ]
    }

..and I want to populate a drop down list with this data, to look like this...

Angular screenshot

I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.

How would I do it ?

My Angular controller would look like this:

function MikesAngularController($scope, $http) {

    $scope.listOfCustomers = null;

    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
         .success(function (data) {
             $scope.listOfCustomers = data.GetAllCustomersResult;
         })
         .error(function (data, status, headers, config) {
             //  Do some error handling here
         });
}

... which fills a "listOfCustomers" variable with this set of JSON data.

Then, in my HTML page, I'd use this:

<div ng-controller='MikesAngularController'>
    <span>Please select a customer:</span>
    <select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>

And that's it. We can now see a list of our JSON data on a web page, ready to be used.

The key to this is in the "ng-options" tag:

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

It's a strange syntax to get your head around !

When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.

The full script for this example can be found here:

JSON data with Angular

Mike

How to pass variable number of arguments to a PHP function

For those looking for a way to do this with $object->method:

call_user_func_array(array($object, 'method_name'), $array);

I was successful with this in a construct function that calls a variable method_name with variable parameters.

Android Stop Emulator from Command Line

Use adb kill-server. It should helps. or

adb -s emulator-5554 emu kill, where emulator-5554 is the emulator name.

For Ubuntu users I found a good command to stop all running emulators (Thanks to @uwe)

adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done

Generate HTML table from 2D JavaScript array

Based on the accepted solution:

function createTable (tableData) {
  const table = document.createElement('table').appendChild(
    tableData.reduce((tbody, rowData) => {
      tbody.appendChild(
        rowData.reduce((tr, cellData) => {
          tr.appendChild(
            document
              .createElement('td')
              .appendChild(document.createTextNode(cellData))
          )
          return tr
        }, document.createElement('tr'))
      )
      return tbody
    }, document.createElement('tbody'))
  )

  document.body.appendChild(table)
}

createTable([
  ['row 1, cell 1', 'row 1, cell 2'],
  ['row 2, cell 1', 'row 2, cell 2']
])

With a simple change it is possible to return the table as HTML element.

Read input from console in Ruby?

you can also pass the parameters through the command line. Command line arguments are stores in the array ARGV. so ARGV[0] is the first number and ARGV[1] the second number

#!/usr/bin/ruby

first_number = ARGV[0].to_i
second_number = ARGV[1].to_i

puts first_number + second_number

and you call it like this

% ./plus.rb 5 6
==> 11

Cannot catch toolbar home button click event

For anyone looking for a Xamarin implementation (since events are done differently in C#), I simply created this NavClickHandler class as follows:

public class NavClickHandler : Java.Lang.Object, View.IOnClickListener
{
    private Activity mActivity;
    public NavClickHandler(Activity activity)
    {
        this.mActivity = activity;
    }
    public void OnClick(View v)
    {
        DrawerLayout drawer = (DrawerLayout)mActivity.FindViewById(Resource.Id.drawer_layout);
        if (drawer.IsDrawerOpen(GravityCompat.Start))
        {
            drawer.CloseDrawer(GravityCompat.Start);
        }
        else
        {
            drawer.OpenDrawer(GravityCompat.Start);
        }
    }
}

Then, assigned a custom hamburger menu button like this:

        SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar.SetDefaultDisplayHomeAsUpEnabled(false);
        this.drawerToggle.DrawerIndicatorEnabled = false;
        this.drawerToggle.SetHomeAsUpIndicator(Resource.Drawable.MenuButton);

And finally, assigned the drawer menu toggler a ToolbarNavigationClickListener of the class type I created earlier:

        this.drawerToggle.ToolbarNavigationClickListener = new NavClickHandler(this);

And then you've got a custom menu button, with click events handled.

How to dump a dict to a json file?

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...

How to open a new tab in GNOME Terminal from command line?

#!/bin/sh

WID=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}')
xdotool windowfocus $WID
xdotool key ctrl+shift+t
wmctrl -i -a $WID

This will auto determine the corresponding terminal and opens the tab accordingly.

How do I enable logging for Spring Security?

Assuming you're using Spring Boot, another option is to put the following in your application.properties:

logging.level.org.springframework.security=DEBUG

This is the same for most other Spring modules as well.

If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.

Here is the application.yml version as well:

logging:
  level:
    org:
      springframework:
        security: DEBUG

How to overlay image with color in CSS?

In helpshift, they used the class home-page as

HTML

<div class="page home-page">...</div>

CSS

.home-page {
    background: transparent url("../images/backgrounds/image-overlay.png") repeat 0 0;
    background: rgba(39,62,84,0.82);
    overflow: hidden;
    height: 100%;
    z-index: 2;
}

you can try similar like this

Show row number in row header of a DataGridView

private void setRowNumber(DataGridView dgv)
{
    foreach (DataGridViewRow row in dgv.Rows)
    {
        row.HeaderCell.Value = (row.Index + 1).ToString();
    }
}

This worked for me.

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

Python Save to file

file = open('Failed.py', 'w')
file.write('whatever')
file.close()

Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block:

with open('Failed.py', 'w') as file:
    file.write('whatever')

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"

Explanation : [How it works]

Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.

Hope it work

Other warning

objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int

Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"

[caution: It may void other warning of 64 Bits architecture conversion].

Export specific rows from a PostgreSQL table as INSERT SQL script

I tried to write a procedure doing that, based on @PhilHibbs codes, on a different way. Please have a look and test.

 CREATE OR REPLACE FUNCTION dump(IN p_schema text, IN p_table text, IN p_where text)
   RETURNS setof text AS
 $BODY$
 DECLARE
     dumpquery_0 text;
     dumpquery_1 text;
     selquery text;
     selvalue text;
     valrec record;
     colrec record;
 BEGIN

     -- ------ --
     -- GLOBAL --
     --   build base INSERT
     --   build SELECT array[ ... ]
     dumpquery_0 := 'INSERT INTO ' ||  quote_ident(p_schema) || '.' || quote_ident(p_table) || '(';
     selquery    := 'SELECT array[';

     <<label0>>
     FOR colrec IN SELECT table_schema, table_name, column_name, data_type
                   FROM information_schema.columns
                   WHERE table_name = p_table and table_schema = p_schema
                   ORDER BY ordinal_position
     LOOP
         dumpquery_0 := dumpquery_0 || quote_ident(colrec.column_name) || ',';
         selquery    := selquery    || 'CAST(' || quote_ident(colrec.column_name) || ' AS TEXT),';
     END LOOP label0;

     dumpquery_0 := substring(dumpquery_0 ,1,length(dumpquery_0)-1) || ')';
     dumpquery_0 := dumpquery_0 || ' VALUES (';
     selquery    := substring(selquery    ,1,length(selquery)-1)    || '] AS MYARRAY';
     selquery    := selquery    || ' FROM ' ||quote_ident(p_schema)||'.'||quote_ident(p_table);
     selquery    := selquery    || ' WHERE '||p_where;
     -- GLOBAL --
     -- ------ --

     -- ----------- --
     -- SELECT LOOP --
     --   execute SELECT built and loop on each row
     <<label1>>
     FOR valrec IN  EXECUTE  selquery
     LOOP
         dumpquery_1 := '';
         IF not found THEN
             EXIT ;
         END IF;

         -- ----------- --
         -- LOOP ARRAY (EACH FIELDS) --
         <<label2>>
         FOREACH selvalue in ARRAY valrec.MYARRAY
         LOOP
             IF selvalue IS NULL
             THEN selvalue := 'NULL';
             ELSE selvalue := quote_literal(selvalue);
             END IF;
             dumpquery_1 := dumpquery_1 || selvalue || ',';
         END LOOP label2;
         dumpquery_1 := substring(dumpquery_1 ,1,length(dumpquery_1)-1) || ');';
         -- LOOP ARRAY (EACH FIELD) --
         -- ----------- --

         -- debug: RETURN NEXT dumpquery_0 || dumpquery_1 || ' --' || selquery;
         -- debug: RETURN NEXT selquery;
         RETURN NEXT dumpquery_0 || dumpquery_1;

     END LOOP label1 ;
     -- SELECT LOOP --
     -- ----------- --

 RETURN ;
 END
 $BODY$
   LANGUAGE plpgsql VOLATILE;

And then :

-- for a range
SELECT dump('public', 'my_table','my_id between 123456 and 123459'); 
-- for the entire table
SELECT dump('public', 'my_table','true');

tested on my postgres 9.1, with a table with mixed field datatype (text, double, int,timestamp without time zone, etc).

That's why the CAST in TEXT type is needed. My test run correctly for about 9M lines, looks like it fail just before 18 minutes of running.

ps : I found an equivalent for mysql on the WEB.

Detect click inside/outside of element with single event handler

Here's a one liner that doesn't require jquery using Node.contains:

// Get arbitrary element with id "my-element"
var myElementToCheckIfClicksAreInsideOf = document.querySelector('#my-element');
// Listen for click events on body
document.body.addEventListener('click', function (event) {
    if (myElementToCheckIfClicksAreInsideOf.contains(event.target)) {
        console.log('clicked inside');
    } else {
        console.log('clicked outside');
    }
});

If you're wondering about the edge case of checking if the click is on the element itself, Node.contains returns true for the element itself (e.g. element.contains(element) === true) so this snippet should always work.

Browser support seems to cover pretty much everything according to that MDN page as well.

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

I also experienced the same error, "NPM package not installed correctly", while creating a Node.js project in Visual Studio 2015.

I resolved my issue by performing two steps:

  1. Delete all files present in this location:

    C:\Users\<Your User Name>\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache
    

    Restart Visual Studio.

  2. Open Visual Studio and go to menu Tools ? NuGet Package Manager ? Package Manager Settings ?

    On the left side: You will see a drop down list: select Node.js, Tools ? Npm ? ClearCache ? *OK

Then again try to create the project. It resolved my issue.

How to count the number of true elements in a NumPy bool array

boolarr.sum(axis=1 or axis=0)

axis = 1 will output number of trues in a row and axis = 0 will count number of trues in columns so

boolarr[[true,true,true],[false,false,true]]
print(boolarr.sum(axis=1))

will be (3,1)

Get IP address of visitors using Flask for Python

See the documentation on how to access the Request object and then get from this same Request object, the attribute remote_addr.

Code example

from flask import request
from flask import jsonify

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
    return jsonify({'ip': request.remote_addr}), 200

For more information see the Werkzeug documentation.

Unmount the directory which is mounted by sshfs in Mac

Don't use umount.

Use

fusermount -u PATH

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


getResourceAsStream() vs FileInputStream

getResourceAsStream is the right way to do it for web apps (as you already learned).

The reason is that reading from the file system cannot work if you package your web app in a WAR. This is the proper way to package a web app. It's portable that way, because you aren't dependent on an absolute file path or the location where your app server is installed.

IF Statement multiple conditions, same statement

if (columnname != a && columnname != b && columnname != c 
        && (columnname != A2 || checkbox.checked))
    {
      "statement 1"
    }

Java optional parameters

varargs could do that (in a way). Other than that, all variables in the declaration of the method must be supplied. If you want a variable to be optional, you can overload the method using a signature which doesn't require the parameter.

private boolean defaultOptionalFlagValue = true;

public void doSomething(boolean optionalFlag) {
    ...
}

public void doSomething() {
    doSomething(defaultOptionalFlagValue);
}

mailto using javascript

With JavaScript you can create a link 'on the fly' using something like:

var mail = document.createElement("a");
mail.href = "mailto:[email protected]";
mail.click();

This is redirected by the browser to some mail client installed on the machine without losing the content of the current window ... and you would not need any API like 'jQuery'.

Why are exclamation marks used in Ruby methods?

It is most accurate to say that methods with a Bang! are the more dangerous or surprising version. There are many methods that mutate without a Bang such as .destroy and in general methods only have bangs where a safer alternative exists in the core lib.

For instance, on Array we have .compact and .compact!, both methods mutate the array, but .compact! returns nil instead of self if there are no nil's in the array, which is more surprising than just returning self.

The only non-mutating method I've found with a bang is Kernel's .exit! which is more surprising than .exit because you cannot catch SystemExit while the process is closing.

Rails and ActiveRecord continues this trend in that it uses bang for more 'surprising' effects like .create! which raises errors on failure.

How to delete multiple rows in SQL where id = (x to y)

If you need to delete based on a list, you can use IN:

DELETE FROM your_table
WHERE id IN (value1, value2, ...);

If you need to delete based on the result of a query, you can also use IN:

DELETE FROM your_table
WHERE id IN (select aColumn from ...);

(Notice that the subquery must return only one column)

If you need to delete based on a range of values, either you use BETWEEN or you use inequalities:

DELETE FROM your_table
WHERE id BETWEEN bottom_value AND top_value;

or

DELETE FROM your_table
WHERE id >= a_value AND id <= another_value;

Installing PIL with pip

I'm having the same problem, but it gets solved with installation of python-dev.

Before installing PIL, run following command:

sudo apt-get install python-dev

Then install PIL:

pip install PIL

Use basic authentication with jQuery and Ajax

According to SharkAlley answer it works with nginx too.

I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:

server {
    server_name example.com;

    location / {
        if ($request_method = OPTIONS ) {
            add_header Access-Control-Allow-Origin "*";
            add_header Access-Control-Allow-Methods "GET, OPTIONS";
            add_header Access-Control-Allow-Headers "Authorization";

            # Not necessary
            #            add_header Access-Control-Allow-Credentials "true";
            #            add_header Content-Length 0;
            #            add_header Content-Type text/plain;

            return 200;
        }

        auth_basic "Restricted";
        auth_basic_user_file /var/.htpasswd;

        proxy_pass http://127.0.0.1:8100;
    }
}

And the JavaScript code is:

var auth = btoa('username:password');
$.ajax({
    type: 'GET',
    url: 'http://example.com',
    headers: {
        "Authorization": "Basic " + auth
    },
    success : function(data) {
    },
});

Article that I find useful:

  1. This topic's answers
  2. http://enable-cors.org/server_nginx.html
  3. http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method/

Example of Mockito's argumentCaptor

The steps in order to make a full check are:

Prepare the captor :

ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);

verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.

verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());

Get the argument passed to collaborator

SomeArgumentClass someArgument = messageCaptor.getValue();

someArgument can be used for assertions

Run text file as commands in Bash

cat /path/* | bash

OR

cat commands.txt | bash

MVC: How to Return a String as JSON

All answers here provide good and working code. But someone would be dissatisfied that they all use ContentType as return type and not JsonResult.

Unfortunately JsonResult is using JavaScriptSerializer without option to disable it. The best way to get around this is to inherit JsonResult.

I copied most of the code from original JsonResult and created JsonStringResult class that returns passed string as application/json. Code for this class is below

public class JsonStringResult : JsonResult
    {
        public JsonStringResult(string data)
        {
            JsonRequestBehavior = JsonRequestBehavior.DenyGet;
            Data = data;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Get request is not allowed!");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                response.Write(Data);
            }
        }
    }

Example usage:

var json = JsonConvert.SerializeObject(data);
return new JsonStringResult(json);

How to find Current open Cursors in Oracle

This could work:

SELECT    sql_text "SQL Query", 
          Count(*) AS "Open Cursors" 
FROM      v$open_cursor 
GROUP BY  sql_text 
HAVING    Count(*) > 2 
ORDER BY  Count(*) DESC; 

adb shell su works but adb root does not

In some developer-friendly ROMs you could just enable Root Access in Settings > Developer option > Root access. After that adb root becomes available. Unfortunately it does not work for most stock ROMs on the market.

Correct mime type for .mp4

When uploading .mp4 file into Perl script, using CGI.pm I see it as video/mp when printing out Content-type for the uploaded file. I hope it will help someone.

Escape double quotes in Java

Escaping the double quotes with backslashes is the only way to do this in Java.

Some IDEs around such as IntelliJ IDEA do this escaping automatically when pasting such a String into a String literal (i.e. between the double quotes surrounding a java String literal)

One other option would be to put the String into some kind of text file that you would then read at runtime

Relative div height

The div take the height of its parent, but since it has no content (expecpt for your divs) it will only be as height as its content.

You need to set the height of the body and html:

HTML:

<div class="block12">
    <div class="block1">1</div>
    <div class="block2">2</div>
</div>
<div class="block3">3</div>

CSS:

body, html {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.block12 {
    width: 100%;
    height: 50%;
    background: yellow;
    overflow: auto;
}
.block1, .block2 {
    width: 50%;
    height: 100%;
    display: inline-block;
    margin-right: -4px;
    background: lightgreen;
}
.block2 { background: lightgray }
.block3 {
    width: 100%;
    height: 50%;
    background: lightblue;
}

And a JSFiddle

Alter SQL table - allow NULL column value

The following MySQL statement should modify your column to accept NULLs.

ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL

How can one display images side by side in a GitHub README.md?

For markdown table syntax see:

https://www.markdownguide.org/extended-syntax/#tables


Quick summary:

To quickly understand the syntax used in other answers, it helps to start from a more complete intuitive and easier to remember syntax, and then a minimalized version with the same result.

Basic example:

| Header A       | Header B       |
| -------------- | -------------- |
| row 1 col 1    | row 1 col 2    |
| row 2 column 1 | row 2 column 2 |

Same result in a more minimalist form (cell widths can vary) :

Header A | Header B
--- | ---
row 1 col 1 | row 1 col 2
row 2 column 1 | row 2 column 2

And more related to the question: side by side images with labels on top:

label 1 | label 2
--- | ---
![](https://...image1.png) | ![](https://...image2.png)

( use :--- , ---: , and :---: for (text) alignment in the column, respectively: left, right, center )

Difference between setTimeout with and without quotes and parentheses

With the parentheses:

setTimeout("alertMsg()", 3000); // It work, here it treat as a function

Without the quotes and the parentheses:

setTimeout(alertMsg, 3000); // It also work, here it treat as a function

And the third is only using quotes:

setTimeout("alertMsg", 3000); // It not work, here it treat as a string

_x000D_
_x000D_
function alertMsg1() {_x000D_
        alert("message 1");_x000D_
    }_x000D_
    function alertMsg2() {_x000D_
        alert("message 2");_x000D_
    }_x000D_
    function alertMsg3() {_x000D_
        alert("message 3");_x000D_
    }_x000D_
    function alertMsg4() {_x000D_
        alert("message 4");_x000D_
    }_x000D_
_x000D_
    // this work after 2 second_x000D_
    setTimeout(alertMsg1, 2000);_x000D_
_x000D_
    // This work immediately_x000D_
    setTimeout(alertMsg2(), 4000);_x000D_
_x000D_
    // this fail_x000D_
    setTimeout('alertMsg3', 6000);_x000D_
_x000D_
    // this work after 8second_x000D_
    setTimeout('alertMsg4()', 8000);
_x000D_
_x000D_
_x000D_

In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.

Hive Alter table change Column Name

Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.

EXAMPLE:

hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;

  MismatchedTokenException(49!=90)
        at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
        at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
        at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
        ...

hive> use databasename;

hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;

OK

How to bind event listener for rendered elements in Angular 2?

@HostListener('window:click', ['$event']) onClick(event){ }

check this below link to detect CapsLock on click, keyup and keydown on current window. No need to add any event in html doc

Detect and warn users about caps lock is on

pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds

See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.

Note that there isn't a list of all the different how options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how by name.

C++ alignment when printing cout <<

Another way to make column aligned is as follows:

using namespace std;

cout.width(20); cout << left << "Artist";
cout.width(20); cout << left << "Title";
cout.width(10); cout << left << "Price";
...
cout.width(20); cout << left << artist;
cout.width(20); cout << left << title;
cout.width(10); cout << left << price;

We should estimate maximum length of values for each column. In this case, values of "Artist" column should not exceed 20 characters and so on.

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

selecting unique values from a column

DISTINCT is always a right choice to get unique values. Also you can do it alternatively without using it. That's GROUP BY. Which has simply add at the end of the query and followed by the column name.

SELECT * FROM buy GROUP BY date,description

How to pass in password to pg_dump?

Or you can set up crontab to run a script. Inside that script you can set an environment variable like this: export PGPASSWORD="$put_here_the_password"

This way if you have multiple commands that would require password you can put them all in the script. If the password changes you only have to change it in one place (the script).

And I agree with Joshua, using pg_dump -Fc generates the most flexible export format and is already compressed. For more info see: pg_dump documentation

E.g.

# dump the database in custom-format archive
pg_dump -Fc mydb > db.dump

# restore the database
pg_restore -d newdb db.dump

How do I check if an object has a key in JavaScript?

You should use hasOwnProperty. For example:

myObj.hasOwnProperty('myKey');

Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:

Object.prototype.hasOwnProperty.call(myObj, 'myKey');

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had this same problem when trying to upgrade pm2 to the latest version.

Thanks to sdm's answer I did npm update npm -g and it did the trick for me.

How to use responsive background image in css3 in bootstrap

Set Responsive and User friendly Background

<style>
body {
background: url(image.jpg);
background-size:100%;
background-repeat: no-repeat;
width: 100%;
}
</style>

JTable - Selected Row click event

Here's how I did it:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            // do some actions here, for example
            // print first column value from selected row
            System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
        }
    });

This code reacts on mouse click and item selection from keyboard.

Python script to convert from UTF-8 to ASCII

UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.

OwinStartup not firing

In my case this Microsoft.Owin.Host.SystemWeb package is present in the project.

But below two tags are not present in web.config.

<add key="owin:AutomaticAppStartup" value="true" />
<add key="owin:appStartup" value="namespace.className.methodName" />

after adding them it works smoothly.

What's the quickest way to multiply multiple cells by another number?

Put the number you want to multiply by in a cell that is not in your range. Select the cell and "Copy" it to the clipboard. Next, select the Range A1:D5, and from the menu choose Edit|Paste Special. A dialog box will appear. In the "Operation" area, select "Multiply" and click "OK".

Behaviour of increment and decrement operators in Python

++ is not an operator. It is two + operators. The + operator is the identity operator, which does nothing. (Clarification: the + and - unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++ operator to work on strings.)

++count

Parses as

+(+count)

Which translates to

count

You have to use the slightly longer += operator to do what you want to do:

count += 1

I suspect the ++ and -- operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:

  • Simpler parsing. Technically, parsing ++count is ambiguous, as it could be +, +, count (two unary + operators) just as easily as it could be ++, count (one unary ++ operator). It's not a significant syntactic ambiguity, but it does exist.
  • Simpler language. ++ is nothing more than a synonym for += 1. It was a shorthand invented because C compilers were stupid and didn't know how to optimize a += 1 into the inc instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.
  • Confusing side-effects. One common newbie error in languages with ++ operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.

How can I open two pages from a single click without using JavaScript?

it is working perfectly by only using html

<p><a href="#"onclick="window.open('http://google.com');window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>

How do I make a JSON object with multiple arrays?

Another example:

[  
[  
    {  
        "@id":1,
        "deviceId":1,
        "typeOfDevice":"1",
        "state":"1",
        "assigned":true
    },
    {  
        "@id":2,
        "deviceId":3,
        "typeOfDevice":"3",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":3,
        "deviceId":4,
        "typeOfDevice":"júuna",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":4,
        "deviceId":5,
        "typeOfDevice":"nffjnff",
        "state":"Regular",
        "assigned":true
    },
    {  
        "@id":5,
        "deviceId":6,
        "typeOfDevice":"44",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":6,
        "deviceId":7,
        "typeOfDevice":"rr",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":7,
        "deviceId":8,
        "typeOfDevice":"j",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":8,
        "deviceId":9,
        "typeOfDevice":"55",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":9,
        "deviceId":10,
        "typeOfDevice":"5",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":10,
        "deviceId":11,
        "typeOfDevice":"5",
        "state":"Excelent",
        "assigned":true
    }
],
1
]

Read the array's

$.each(data[0], function(i, item) {
         data[0][i].deviceId + data[0][i].typeOfDevice  + data[0][i].state +  data[0][i].assigned 
    });

Use http://www.jsoneditoronline.org/ to understand the JSON code better

Finding modified date of a file/folder

PowerShell code to find all document library files modified from last 2 days.

$web = Get-SPWeb -Identity http://siteName:9090/ 
        $list = $web.GetList("http://siteName:9090/Style Library/")
        $folderquery =  New-Object Microsoft.SharePoint.SPQuery  
        $foldercamlQuery =  
        '<Where>   <Eq> 
                <FieldRef Name="ContentType" />  <Value Type="text">Folder</Value> 
            </Eq> </Where>' 
        $folderquery.Query = $foldercamlQuery 
        $folders = $list.GetItems($folderquery) 
        foreach($folderItem in $folders) 
        { 
            $folder = $folderItem.Folder
            if($folder.ItemCount -gt 0){ 
            Write-Host " find Item count " $folder.ItemCount
                $oldest = $null
                $files = $folder.Files

                $date = (Get-Date).AddDays(-2).ToString(“MM/dd/yyyy”)
                foreach ($file in $files){ 
                    if($file.Item["Modified"]-Ge $date)
                    {
                        Write-Host "Last 2 days modified folder name:"   $folder   " File Name: "  $file.Item["Name"]   " Date of midified: "  $file.Item["Modified"] 
                    } 
                } 
            } 
            else
             { 
                Write-Warning "$folder['Name'] is empty" 
            } 
        }

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

If u still facing problem then try to uninstall application using command prompt. just add command adb uninstall com.example.yourpackagename then try to re-install again.It works!

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

You import one dependency, and this dependency is dependent on com.sun.jmx:jmxri:jar:1.2.1 and others, but com.sun.jmx:jmxri:jar:1.2.1 cannot be found in central repository,

so you'd better try to import another version.

Here suppose your dependency may be log4j, and you can try to import log4j:log4j:jar:1.2.13.

How to select and change value of table cell with jQuery?

I wanted to change the column value in a specific row. Thanks to above answers and after some serching able to come up with below,

var dataTable = $("#yourtableid");
var rowNumber = 0;  
var columnNumber= 2;   
dataTable[0].rows[rowNumber].cells[columnNumber].innerHTML = 'New Content';

What is the use of printStackTrace() method in Java?

printStackTrace() helps the programmer to understand where the actual problem occurred. It helps to trace the exception. it is printStackTrace() method of Throwable class inherited by every exception class. This method prints the same message of e object and also the line number where the exception occurred.

The following is an another example of print stack of the Exception in Java.

public class Demo {
   public static void main(String[] args) {
      try {
         ExceptionFunc();
      } catch(Throwable e) {
         e.printStackTrace();
      }
   }
   public static void ExceptionFunc() throws Throwable {
      Throwable t = new Throwable("This is new Exception in Java...");

      StackTraceElement[] trace = new StackTraceElement[] {
         new StackTraceElement("ClassName","methodName","fileName",5)
      };
      t.setStackTrace(trace);
      throw t;
   }
}

java.lang.Throwable: This is new Exception in Java... at ClassName.methodName(fileName:5)

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

The HTTP Content-Type for .ogg should be application/ogg (video/ogg for .ogv) and for .mp4 it should be video/mp4. You can check using the Web Sniffer.

Custom height Bootstrap's navbar

your markup was a bit messed up. Here's the styles you need and proper html

CSS:

.navbar-brand,
.navbar-nav li a {
    line-height: 150px;
    height: 150px;
    padding-top: 0;
}

HTML:

<nav class="navbar navbar-default">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>

        <a class="navbar-brand" href="#"><img src="img/logo.png" /></a>
    </div>

    <div class="collapse navbar-collapse">
        <ul class="nav navbar-nav">
            <li><a href="">Portfolio</a></li>
            <li><a href="">Blog</a></li>
            <li><a href="">Contact</a></li>
        </ul>
    </div>
</nav>

Or check out the fiddle at: http://jsfiddle.net/TP5V8/1/

Install GD library and freetype on Linux

Things are pretty much simpler unless they are made confusing.

To Install GD library in Ubuntu

sudo apt-get install php5-gd

To Install Freetype in Ubuntu

sudo apt-get install libfreetype6-dev:i386

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

How to find encoding of a file via script on Linux?

file -bi <file name>

If you like to do this for a bunch of files

for f in `find | egrep -v Eliminate`; do echo "$f" ' -- ' `file -bi "$f"` ; done

getting the index of a row in a pandas apply function

To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key name and requires that you specify axis=1 (because the lambda processes the columns of a row and not the rows of a column).

Working example (pandas 0.23.4):

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
   b  c
a      
1  2  3
4  5  6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
   b  c  index_x10
a                 
1  2  3         10
4  5  6         40

How to compile and run a C/C++ program on the Android system

if you have installed NDK succesfully then start with it sample application

http://developer.android.com/sdk/ndk/overview.html#samples

if you are interested another ways of this then may this will help

http://shareprogrammingtips.blogspot.com/2018/07/cross-compile-cc-based-programs-and-run.html

I also want to know is it possible to push the compiled binary into android device or AVD and run using the terminal of the android device or AVD?

here you can see NestedVM

NestedVM provides binary translation for Java Bytecode. This is done by having GCC compile to a MIPS binary which is then translated to a Java class file. Hence any application written in C, C++, Fortran, or any other language supported by GCC can be run in 100% pure Java with no source changes.


Example: Cross compile Hello world C program and run it on android

Tooltips with Twitter Bootstrap

Add this into your header

<script>
    //tooltip
    $(function() {
        var tooltips = $( "[title]" ).tooltip();
        $(document)(function() {
            tooltips.tooltip( "open" );
        });
    });
</script>

Then just add the attribute title="your tooltip" to any element

how to prevent "directory already exists error" in a makefile when using mkdir

On UNIX Just use this:

mkdir -p $(OBJDIR)

The -p option to mkdir prevents the error message if the directory exists.

Refused to execute script, strict MIME type checking is enabled?

My problem was that I have been putting the CSS files in the scripts definition area just above the end of the Try to check the files spots within your pages

Is it correct to use alt tag for an anchor link?

You should use the title attribute for anchor tags if you wish to apply descriptive information similarly as you would for an alt attribute. The title attribute is valid on anchor tags and is serves no other purpose than providing information about the linked page.

W3C recommends that the value of the title attribute should match the value of the title of the linked document but it's not mandatory.

http://www.w3.org/MarkUp/1995-archive/Elements/A.html


Alternatively, and likely to be more beneficial, you can use the ARIA accessibility attribute aria-label (not to be confused with aria-labeledby). aria-label serves the same function as the alt attribute does for images but for non-image elements and includes some measure of optimization since your optimizing for screen readers.

http://www.w3.org/WAI/GL/wiki/Using_aria-label_to_provide_labels_for_objects


If you want to describe an anchor tag though, it's usually appropriate to use the rel or rev tag but your limited to specific values, they should not be used for human readable descriptions.

Rel serves to describe the relationship of the linked page to the current page. (e.g. if the linked page is next in a logical series it would be rel=next)

The rev attribute is essentially the reverse relationship of the rel attribute. Rev describes the relationship of the current page to the linked page.

You can find a list of valid values here: http://microformats.org/wiki/existing-rel-values

Set value to an entire column of a pandas dataframe

Assuming your Data frame is like 'Data' you have to consider if your data is a string or an integer. Both are treated differently. So in this case you need be specific about that.

import pandas as pd

data = [('001','xxx'), ('002','xxx'), ('003','xxx'), ('004','xxx'), ('005','xxx')]

df = pd.DataFrame(data,columns=['issueid', 'industry'])

print("Old DataFrame")
print(df)

df.loc[:,'industry'] = str('yyy')

print("New DataFrame")
print(df)

Now if want to put numbers instead of letters you must create and array

list_of_ones = [1,1,1,1,1]
df.loc[:,'industry'] = list_of_ones
print(df)

Or if you are using Numpy

import numpy as np
n = len(df)
df.loc[:,'industry'] = np.ones(n)
print(df)

Vertically aligning a checkbox

Vertical alignment only works on inline elements. If you float it, then I don't think it is treated as part of that stream of inline elements any more.

Make the label an inline-block, and use vertical alignment on both the label and the input to align their middles. Then, assuming it is okay to have a specific width on the labels and checkboxes, use relative positioning instead of floating to swap them (jsFiddle demo):

input {
    width: 20px;

    position: relative;
    left: 200px;

    vertical-align: middle;
}

label {  
    width: 200px;

    position: relative;
    left: -20px;

    display: inline-block;
    vertical-align: middle;
}

How can I output UTF-8 from Perl?

You also want to say, that strings in your code are utf-8. See Why does modern Perl avoid UTF-8 by default?. So set not only PERL_UNICODE=SDAL but also PERL5OPT=-Mutf8.

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

Make sure you import csv file using Pandas

import pandas as pd

condition = pd.isnull(data[i][j])

How to use the 'main' parameter in package.json?

Just think of it as the "starting point".

In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.

For example

public class IamMain  // when export and require this guy
{
    public IamMain()  // this is "main"
    {...}

    ...   // many others such as function, properties, etc.
}

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

-if gradle.properties not available then first add that file and add android.useDeprecatedNdk=true

-use this code in build.gradle

defaultConfig {
    applicationId 'com.example.application'
    minSdkVersion 16
    targetSdkVersion 21
    versionCode 11
    versionName "1.1"
    ndk {
        abiFilters "armeabi"
    }
}

`

Importing csv file into R - numeric values read as characters

I had a similar problem. Based on Joshua's premise that excel was the problem I looked at it and found that the numbers were formatted with commas between every third digit. Reformatting without commas fixed the problem.

Applying .gitignore to committed files

Follow these steps:

  1. Add path to gitignore file

  2. Run this command

    git rm -r --cached foldername
    
  3. commit changes as usually.

ISO C90 forbids mixed declarations and code in C

I think you should move the variable declaration to top of block. I.e.

{
    foo();
    int i = 0;
    bar();
}

to

{
    int i = 0;
    foo();
    bar();
}

No grammar constraints (DTD or XML schema) detected for the document

  1. copy your entire code in notepad.
  2. temporarily save the file with any name [while saving the file use "encoding" = UTF-8 (or higher but UTF)].
  3. close the file.
  4. open it again.
  5. copy paste it back on your code.

error must be gone.

How to declare or mark a Java method as deprecated?

Use @Deprecated on method. Don't forget about clarifying javadoc field:

/**
 * Does some thing in old style.
 *
 * @deprecated use {@link #new()} instead.  
 */
@Deprecated
public void old() {
// ...
}

How do I check if a number is a palindrome?

Here is a solution usings lists as stacks in python :

def isPalindromicNum(n):
    """
        is 'n' a palindromic number?
    """
    ns = list(str(n))
    for n in ns:
        if n != ns.pop():
            return False
    return True

popping the stack only considers the rightmost side of the number for comparison and it fails fast to reduce checks

Calling a javascript function recursively

Using Named Function Expressions:

You can give a function expression a name that is actually private and is only visible from inside of the function ifself:

var factorial = function myself (n) {
    if (n <= 1) {
        return 1;
    }
    return n * myself(n-1);
}
typeof myself === 'undefined'

Here myself is visible only inside of the function itself.

You can use this private name to call the function recursively.

See 13. Function Definition of the ECMAScript 5 spec:

The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).

Using arguments.callee:

Alternatively you could use arguments.callee to refer to the current function:

var factorial = function (n) {
    if (n <= 1) {
        return 1;
    }
    return n * arguments.callee(n-1);
}

The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:

(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

I think Quirksmode has all the answers you need (different browsers bubbling behaviour and the mouseenter/mouseleave events), but I think the most common conclusion to that event bubbling mess is the use of a framework like JQuery or Mootools (which has the mouseenter and mouseleave events, which are exactly what you intuited would happen).

Have a look at how they do it, if you want, do it yourself
or you can create your custom "lean mean" version of Mootools with just the event part (and its dependencies).

import an array in python

Checkout the entry on the numpy example list. Here is the entry on .loadtxt()

>>> from numpy import *
>>>
>>> data = loadtxt("myfile.txt")                       # myfile.txt contains 4 columns of numbers
>>> t,z = data[:,0], data[:,3]                         # data is 2D numpy array
>>>
>>> t,x,y,z = loadtxt("myfile.txt", unpack=True)                  # to unpack all columns
>>> t,z = loadtxt("myfile.txt", usecols = (0,3), unpack=True)     # to select just a few columns
>>> data = loadtxt("myfile.txt", skiprows = 7)                    # to skip 7 rows from top of file
>>> data = loadtxt("myfile.txt", comments = '!')                  # use '!' as comment char instead of '#'
>>> data = loadtxt("myfile.txt", delimiter=';')                   # use ';' as column separator instead of whitespace
>>> data = loadtxt("myfile.txt", dtype = int)                     # file contains integers instead of floats

How to get the selected date of a MonthCalendar control in C#

I just noticed that if you do:

monthCalendar1.SelectionRange.Start.ToShortDateString() 

you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.

It's opposite to:

monthCalendar1.SelectionRange.Start.ToString()

//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)

Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.

Scroll to bottom of Div on page load (jQuery)

You can use below code to scroll to bottom of div on page load.

$(document).ready(function(){
  $('div').scrollTop($('div').scrollHeight);
});

Are there pointers in php?

No, As others said, "There is no Pointer in PHP." and I add, there is nothing RAM_related in PHP.

And also all answers are clear. But there were points being left out that I could not resist!

There are number of things that acts similar to pointers

  • eval construct (my favorite and also dangerous)
  • $GLOBALS variable
  • Extra '$' sign Before Variables (Like prathk mentioned)
  • References

First one

At first I have to say that PHP is really powerful language, knowing there is a construct named "eval", so you can create your PHP code while running it! (really cool!)

although there is the danger of PHP_Injection which is far more destructive that SQL_Injection. Beware!

example:

Code:

$a='echo "Hello World.";';
eval ($a);

Output

Hello World.

So instead of using a pointer to act like another Variable, You Can Make A Variable From Scratch!


Second one

$GLOBAL variable is pretty useful, You can access all variables by using its keys.

example:

Code:

$three="Hello";$variable=" Amazing ";$names="World";
$arr = Array("three","variable","names");
foreach($arr as $VariableName)
    echo $GLOBALS[$VariableName];

Output

Hello Amazing World

Note: Other superglobals can do the same trick in smaller scales.


Third one

You can add as much as '$'s you want before a variable, If you know what you're doing.

example:

Code:

$a="b";
$b="c";
$c="d";
$d="e";
$e="f";

echo $a."-";
echo $$a."-";   //Same as $b
echo $$$a."-";  //Same as $$b or $c
echo $$$$a."-"; //Same as $$$b or $$c or $d
echo $$$$$a;    //Same as $$$$b or $$$c or $$d or $e

Output

b-c-d-e-f


Last one

Reference are so close to pointers, but you may want to check this link for more clarification.

example 1:

Code:

$a="Hello";
$b=&$a;
$b="yello";
echo $a;

Output

yello

example 2:

Code:

function junk(&$tion)
{$GLOBALS['a'] = &$tion;}
$a="-Hello World<br>";
$b="-To You As Well";
echo $a;
junk($b);
echo $a;

Output

-Hello World

-To You As Well

Hope It Helps.

Error: Cannot find module html

Use

res.sendFile()

instead of

res.render().

What your trying to do is send a whole file.

This worked for me.

How do I resolve "Cannot find module" error using Node.js?

In my case I had UNMET PEER DEPENDENCY redux@^3.0.0 causing this error message, see all of them and install missing modules again using --save

npm install redux --save

jQuery-UI datepicker default date

jQuery UI Datepicker is coded to always highlight the user's local date using the class ui-state-highlight. There is no built-in option to change this.

One method, described similarly in other answers to related questions, is to override the CSS for that class to match ui-state-default of your theme, for example:

.ui-state-highlight {
    border: 1px solid #d3d3d3;
    background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;
    color: #555555;
}

However this isn't very helpful if you are using dynamic themes, or if your intent is to highlight a different day (e.g., to have "today" be based on your server's clock rather than the client's).

An alternative approach is to override the datepicker prototype that is responsible for highlighting the current day.

Assuming that you are using a minimized version of the UI javascript, the following snippets can address these concerns.


If your goal is to prevent highlighting the current day altogether:

// copy existing _generateHTML method
var _generateHTML = jQuery.datepicker.constructor.prototype._generateHTML;
// remove the string "ui-state-highlight"
_generateHtml.toString().replace(' ui-state-highlight', '');
// and replace the prototype method
eval('jQuery.datepicker.constructor.prototype._generateHTML = ' + _generateHTML);

This changes the relevant code (unminimized for readability) from:

[...](printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + [...]

to

[...](printDate.getTime() == today.getTime() ? '' : '') + [...]

If your goal is to change datepicker's definition of "today":

var useMyDateNotYours = '07/28/2014';
// copy existing _generateHTML method
var _generateHTML = jQuery.datepicker.constructor.prototype._generateHTML;
// set "today" to your own Date()-compatible date
_generateHTML.toString().replace('new Date,', 'new Date(useMyDateNotYours),');
// and replace the prototype method
eval('jQuery.datepicker.constructor.prototype._generateHTML = ' + _generateHTML);

This changes the relevant code (unminimized for readability) from:

[...]var today = new Date();[...]

to

[...]var today = new Date(useMyDateNotYours);[...]
// Note that in the minimized version, the line above take the form `L=new Date,`
// (part of a list of variable declarations, and Date is instantiated without parenthesis)

Instead of useMyDateNotYours you could of course also instead inject a string, function, or whatever suits your needs.

javax.websocket client simple example

TooTallNate has a simple client side https://github.com/TooTallNate/Java-WebSocket

Just add the java_websocket.jar in the dist folder into your project.

 import org.java_websocket.client.WebSocketClient;
 import org.java_websocket.drafts.Draft_10;
 import org.java_websocket.handshake.ServerHandshake;
 import org.json.JSONException;
 import org.json.JSONObject;

  WebSocketClient mWs = new WebSocketClient( new URI( "ws://socket.example.com:1234" ), new Draft_10() )
{
                    @Override
                    public void onMessage( String message ) {
                     JSONObject obj = new JSONObject(message);
                     String channel = obj.getString("channel");
                    }

                    @Override
                    public void onOpen( ServerHandshake handshake ) {
                        System.out.println( "opened connection" );
                    }

                    @Override
                    public void onClose( int code, String reason, boolean remote ) {
                        System.out.println( "closed connection" );
                    }

                    @Override
                    public void onError( Exception ex ) {
                        ex.printStackTrace();
                    }

                };
 //open websocket
 mWs.connect();
 JSONObject obj = new JSONObject();
 obj.put("event", "addChannel");
 obj.put("channel", "ok_btccny_ticker");
 String message = obj.toString();
 //send message
 mWs.send(message);

// and to close websocket

 mWs.close();

How do you display JavaScript datetime in 12 hour AM/PM format?

Updated for more compression

const formatAMPM = (date) => {
  let hours = date.getHours();
  let minutes = date.getMinutes();    
  const ampm = hours >= 12 ? 'pm' : 'am';

  hours %= 12;
  hours = hours || 12;    
  minutes = minutes < 10 ? `0${minutes}` : minutes;

  const strTime = `${hours}:${minutes} ${ampm}`;

  return strTime;
};

console.log(formatAMPM(new Date()));

Is there such a thing as min-font-size and max-font-size?

I am coming a bit late here, I don't get that much credit for it, I am just doing a mix of the answers below because I was forced to do that for a project.

So to answer the question : There is no such thing as this CSS property. I don't know why, but I think it's because they are afraid of a misused of this property, but I don't find any use case where it can be a serious problem.

Whatever, what are the solutions ?

Two tools will allow us to do that : media queries ans vw property

1) There is a "fool" solution consisting in making a media query for every step we eant in our css, changing font from a fixed amount to another fixed amount. It works, but it is very boring to do, and you don't have a smooth linear aspect.

2) As AlmostPitt explained, there is a brillant solution for the minima :

font-size: calc(7px + .5vw);

Minimum here would be 7px in addition to 0.5% of the view width. That is already really cool and working in most of cases. It does not require any media query, you just have to spend some time finding the right parameters.

As you noticed it is a linear function, basic maths learn you that two points already find you the parameters. Then just fix the font-size in px you want for very large screens and for mobile version, then calculate if you want to do a scientific method. Thought, it is absolutely not necessary and you can just go by trying.

3) Let's suppose you have a very boring client (like me) who absolutely wants a title to be one line and no more. If you used AlmostPitt solution, then you are in trouble because your font will keep growing, and if you have a fixed width container (like bootstrap stoping at 1140px or something in large windows). Here I suggest you to use also a media query. In fact you can just find the amout of px size maximum you can handle in your container before the aspect become unwanted (pxMax). This will be your maximum. Then you just have to find the exact screen width you must stop (wMax). (I let you inverse a linear function on your own).

After that just do

@media (min-width: [wMax]px) {
    h2{
        font-size: [pxMax]px;
    }
}

Then it is perfectly linear and your font-size stop growing ! Notice that you don't need to put your previous css property (calc...) in a media query under wMax because media query are considered as more imnportant and it will overwrite the previous property.

I don't think it is useful to make a snippet for this, as you would have trouble to make it to whole screen and it is not rocket science afterall.

Hope this could help others, and don't forget to thank AlmostPitt for his solution.

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

For some of you skipping library will works

project(":libABC") {
    apply plugin: 'org.sonarqube'
    sonarqube {
        skipProject = true
    }
}

What's the difference between process.cwd() vs __dirname?

process.cwd() returns the current working directory,

i.e. the directory from which you invoked the node command.

__dirname returns the directory name of the directory containing the JavaScript source code file

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

Exception from HRESULT: 0x800A03EC Error

I know this is old but just to pitch in my experience. I just ran into it this morning. Turns our my error has nothing to do with .xls line limit or array index. It is caused by an incorrect formula.

I was exporting from database to Excel a sheet about my customers. Someone fill in the customer name as =90Erickson-King and apparently this is fine as a string-type field in the database, however will result in an error as a formula in Excel. Instead of showing #N/A like when you're using Excel, the program just froze and spilt that 0x800A03EC error a while later.

I corrected this by deleting the equal sign and the dash in the customer's name. After that exporting went well.

I guess this error code is a bit too general as people are seen reporting quite a range of different possible causes.

ReactJS lifecycle method inside a function Component

According to the documentation:

import React, { useState, useEffect } from 'react'
// Similar to componentDidMount and componentDidUpdate:

useEffect(() => {


});

see React documentation

How to get CRON to call in the correct PATHs

You should put full paths in your crontab. That's the safest option.
If you don't want to do that you can put a wrapper script around your programs, and set the PATH in there.

e.g.

01 01 * * * command

becomes:

01 01 * * * /full/path/to/command

Also anything called from cron should be be very careful about the programs it runs, and probably set its own choice for the PATH variable.

EDIT:

If you don't know where the command is that you want execute which <command> from your shell and it'll tell you the path.

EDIT2:

So once your program is running, the first thing it should do is set PATH and any other required variable (e.g. LD_LIBRARY_PATH) to the values that are required for the script to run.
Basically instead of thinking how to modify the cron environment to make it more suitable for your program/script - make your script handle the environment it's given, by setting an appropriate one when it starts.

Python convert decimal to hex

To get a pure hex value this might be useful. It's based on Joe's answer:

def gethex(decimal):
    return hex(decimal)[2:]

The simplest possible JavaScript countdown timer?

If you want a real timer you need to use the date object.

Calculate the difference.

Format your string.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}

Example

Jsfiddle

not so precise timer

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);

JsFiddle

An example of how to use getopts in bash

POSIX 7 example

It is also worth checking the example from the standard: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html

aflag=
bflag=
while getopts ab: name
do
    case $name in
    a)    aflag=1;;
    b)    bflag=1
          bval="$OPTARG";;
    ?)   printf "Usage: %s: [-a] [-b value] args\n" $0
          exit 2;;
    esac
done
if [ ! -z "$aflag" ]; then
    printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
    printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"

And then we can try it out:

$ sh a.sh
Remaining arguments are: 
$ sh a.sh -a
Option -a specified
Remaining arguments are: 
$ sh a.sh -b
No arg for -b option
Usage: a.sh: [-a] [-b value] args
$ sh a.sh -b myval
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh -a -b myval
Option -a specified
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh remain
Remaining arguments are: remain
$ sh a.sh -- -a remain
Remaining arguments are: -a remain

Tested in Ubuntu 17.10, sh is dash 0.5.8.

"Object doesn't support this property or method" error in IE11

Best way to solve this until a fix is available (if a fix comes) is to force IE compatibility mode on the user.

Use <META http-equiv="X-UA-Compatible" content="IE=9"> ideally in the masterpage so all pages in your site get the workaround.

Streaming video from Android camera to server

Depending by your budget, you can use a Raspberry Pi Camera that can send images to a server. I add here two tutorials where you can find many more details:

This tutorial show you how to use a Raspberry Pi Camera and display images on Android device

This is the second tutorial where you can find a series of tutorial about real-time video streaming between camera and android device

How can I merge properties of two JavaScript objects dynamically?

You can use Object.assign method. For example:

var result = Object.assign(obj1, obj2);

Also, note that it creates a shallow copy of the object.

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

Change GridView row color based on condition

protected void DrugGridView_RowDataBound(object sender, GridViewRowEventArgs e)

{
    // To check condition on integer value
    if (Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "Dosage")) == 50)
    {
      e.Row.BackColor = System.Drawing.Color.Cyan;
    }
}

How to hide output of subprocess in Python 2.7

As of Python3 you no longer need to open devnull and can call subprocess.DEVNULL.

Your code would be updated as such:

import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)

Config Error: This configuration section cannot be used at this path

i solved this issue

go to cmd and execute aspnet_regiis -i

hope it helpful to someone.

%Like% Query in spring JpaRepository

You can have one alternative of using placeholders as:

@Query("Select c from Registration c where c.place LIKE  %?1%")
List<Registration> findPlaceContainingKeywordAnywhere(String place);

Vim autocomplete for Python

I ran into this on my Mac using the MacPorts vim with +python. Problem was that the MacPorts vim will only bind to python 2.5 with +python, while my extensions were installed under python 2.7. Installing the extensions using pip-2.5 solved it.

Running bash script from within python

Actually, you just have to add the shell=True argument:

subprocess.call("sleep.sh", shell=True)

But beware -

Warning Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

source

How to make a <ul> display in a horizontal row

List items are normally block elements. Turn them into inline elements via the display property.

In the code you gave, you need to use a context selector to make the display: inline property apply to the list items, instead of the list itself (applying display: inline to the overall list will have no effect):

#ul_top_hypers li {
    display: inline;
}

Here is the working example:

_x000D_
_x000D_
#div_top_hypers {_x000D_
    background-color:#eeeeee;_x000D_
    display:inline;      _x000D_
}_x000D_
#ul_top_hypers li{_x000D_
    display: inline;_x000D_
}
_x000D_
<div id="div_top_hypers">_x000D_
    <ul id="ul_top_hypers">_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Inbox</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Compose</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Reports</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Preferences</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> logout</a></li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

Simple DatePicker-like Calendar

jquery ui has a great datepicker you can find it here

http://jqueryui.com/demos/datepicker/

you can use

http://jqueryui.com/demos/datepicker/#event-onSelect

to make your own actions when a date is picked

and if you want it to open without a form you could create a form that's hidden and then bind a click event to it like this

$("button").click(function() {
    $(inputselector).datepicker('show');
});

JQuery Ajax POST in Codeigniter

$(document).ready(function(){   

    $("#send").click(function()
    {       
     $.ajax({
         type: "POST",
         url: base_url + "chat/post_action", 
         data: {textbox: $("#textbox").val()},
         dataType: "text",  
         cache:false,
         success: 
              function(data){
                alert(data);  //as a debugging message.
              }
          });// you have missed this bracket
     return false;
 });
 });

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

Try like this way,

Step 1: First check who you are? it will return current user name e.g ubuntu

$ whoami 

Step 2: Then set permission to your current user, in that case, ubuntu by

sudo chown -R ubuntu .git/

BACKUP LOG cannot be performed because there is no current database backup

Simply you can use this method:

  1. If you have a database with same name: WIN+R -> services.msc -> SQL SERVER(MSSQLSERVER) -> Stop
  2. Go to your MySQL Data folder path and delete previews database files
  3. Start sql service
  4. Right click on database and select Restore database
  5. in Files tab change Data file folder and Log file folder
  6. Click on OK to restore your database

my problem was solved with this method BY...

How to programmatically send a 404 response with Express/Node?

Updated Answer for Express 4.x

Rather than using res.send(404) as in old versions of Express, the new method is:

res.sendStatus(404);

Express will send a very basic 404 response with "Not Found" text:

HTTP/1.1 404 Not Found
X-Powered-By: Express
Vary: Origin
Content-Type: text/plain; charset=utf-8
Content-Length: 9
ETag: W/"9-nR6tc+Z4+i9RpwqTOwvwFw"
Date: Fri, 23 Oct 2015 20:08:19 GMT
Connection: keep-alive

Not Found

Replacing &nbsp; from javascript dom text node

var text = "&quot;&nbsp;&amp;&lt;&gt;";
text = text.replaceHtmlEntites();

String.prototype.replaceHtmlEntites = function() {
var s = this;
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {"nbsp": " ","amp" : "&","quot": "\"","lt"  : "<","gt"  : ">"};
return ( s.replace(translate_re, function(match, entity) {
  return translate[entity];
}) );
};

try this.....this worked for me

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

The most important rationale for avoiding ++ or -- is that the operators return values and cause side effects at the same time, making it harder to reason about the code.

For efficiency's sake, I prefer:

  • ++i when not using the return value (no temporary)
  • i++ when using the return value (no pipeline stall)

I am a fan of Mr. Crockford, but in this case I have to disagree. ++i is 25% less text to parse than i+=1 and arguably clearer.

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

SQL Server String or binary data would be truncated

I am going to add one other possible cause of this error just because no one has mentioned it and it might help some future person (since the OP has found his answer). If the table you are inserting into has triggers, it could be the trigger is generating the error. I have seen this happen when table field definitions were changed, but audit tables were not.

How to insert a string which contains an "&"

I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far.

Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name.

SET DEFINE OFF will stop sqlplus interpreting & this way.

But what if you need to use sqlplus variables and literal & characters?

  • You need SET DEFINE ON to make variables work
  • And SET ESCAPE ON to escape uses of &.

e.g.

set define on
set escape on

define myvar=/forth

select 'back\\ \& &myvar' as swing from dual;

Produces:

old   1: select 'back\\ \& &myvar' from dual
new   1: select 'back\ & /forth' from dual

SWING
--------------
back\ & /forth

If you want to use a different escape character:

set define on
set escape '#'

define myvar=/forth

select 'back\ #& &myvar' as swing from dual;

When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first:

set escape off
set escape '#'

How to Return partial view of another controller by controller?

Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared folder if shared between controllers (hence the name).

"Answer" (but not recommended - see below):

You can refer to views/partial views from another controller, by specifying the full path (including extension) like:

return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

or a relative path (no extension), based on the answer by @Max Toro

return PartialView("../ABC/XXX", zyxmodel);

BUT THIS IS NOT A GOOD IDEA ANYWAY

*Note: These are the only two syntax that work. not ABC\\XXX or ABC/XXX or any other variation as those are all relative paths and do not find a match.

Better Alternatives:

You can use Html.Renderpartial in your view instead, but it requires the extension as well:

Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);

Use @Html.Partial for inline Razor syntax:

@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)

You can use the ../controller/view syntax with no extension (again credit to @Max Toro):

@Html.Partial("../ControllerName/ViewName", modeldata)

Note: Apparently RenderPartial is slightly faster than Partial, but that is not important.

If you want to actually call the other controller, use:

@Html.Action("action", "controller", parameters)

Recommended solution: @Html.Action

My personal preference is to use @Html.Action as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).

You would normally pass just the required key values (like any other view) e.g. for your example:

@Html.Action("XXX", "ABC", new {id = model.xyzId })

This will execute the ABC.XXX action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).

Update Sep 2014:

I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action and controller names. To that end I added this simple View extension method to UrlHelper so you can say return PartialView(Url.View("actionName", "controllerName"), modelData):

public static class UrlHelperExtension
{
    /// <summary>
    /// Return a view path based on an action name and controller name
    /// </summary>
    /// <param name="url">Context for extension method</param>
    /// <param name="action">Action name</param>
    /// <param name="controller">Controller name</param>
    /// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
    public static string View(this UrlHelper url, string action, string controller)
    {
        return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
    }
}

How do I check when a UITextField changes?

You can use this delegate method from UITextFieldDelegate. It fires with every character change.

(Objective C) textField:shouldChangeCharactersInRange:replacementString:
(Swift) textField(_:shouldChangeCharactersInRange:replacementString:)

However THIS ONLY FIRES BEFORE a change is made (indeed, a change is only made if you do return true from here).

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

SQL Client for Mac OS X that works with MS SQL Server

Not sure about open-source, but I've heard good things about http://www.advenio.com/sqlgrinder/ (not tried it, I prefer to write Python scripts to try things out rather than use GUIs;-).

Collections.emptyList() vs. new instance

Starting with Java 5.0 you can specify the type of element in the container:

Collections.<Foo>emptyList()

I concur with the other responses that for cases where you want to return an empty list that stays empty, you should use this approach.

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I used this config:

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v2.0"/>
    <supportedRuntime version="v4.0"/>
</startup>

Worked for me

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

Is it possible to set UIView border properties from interface builder?

Actually you can set some properties of a view's layer through interface builder. I know that I can set a layer's borderWidth and cornerRadius through xcode. borderColor doesn't work, probably because the layer wants a CGColor instead of a UIColor.

You might have to use Strings instead of numbers, but it works!

layer.cornerRadius
layer.borderWidth
layer.borderColor

Update: layer.masksToBounds = true

example

Update: select appropriate Type for Keypath:

enter image description here

Running Selenium Webdriver with a proxy in Python

How about something like this

PROXY = "149.215.113.110:70"

webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    "noProxy":None,
    "proxyType":"MANUAL",
    "class":"org.openqa.selenium.Proxy",
    "autodetect":False
}

# you have to use remote, otherwise you'll have to code it yourself in python to 
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.FIREFOX)

You can read more about it here.

Execute and get the output of a shell command in node.js

You're looking for child_process

var exec = require('child_process').exec;
var child;

child = exec(command,
   function (error, stdout, stderr) {
      console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
      if (error !== null) {
          console.log('exec error: ' + error);
      }
   });

As pointed out by Renato, there are some synchronous exec packages out there now too, see sync-exec that might be more what yo're looking for. Keep in mind though, node.js is designed to be a single threaded high performance network server, so if that's what you're looking to use it for, stay away from sync-exec kinda stuff unless you're only using it during startup or something.

jQuery override default validation error message display (Css) Popup/Tooltip like

That answer really helped me, in my case i had to filter some elements out and have special aligment on their error div,

errorPlacement:function(error,element) {
    if (element.attr("id") == "special_element") {
        // special align
    } else { // default error scheme
        error.insertAfter(element);
    }
}

ArrayList: how does the size increase?

Context java 8

I give my answer here in the context of Oracle java 8 implementation, since after reading all the answers, I found that an answer in the context of java 6 has given by gmgmiller, and another answer has been given in the context of java 7. But how java 8 implementes the size increasement has not been given.

In java 8, the size increasement behavior is the same as java 6, see the grow method of ArrayList:

   private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

the key code is this line:

int newCapacity = oldCapacity + (oldCapacity >> 1);

So clearly, the growth factor is also 1.5, the same as java 6.

How to make scipy.interpolate give an extrapolated result beyond the input range?

Standard interpolate + linear extrapolate:

    def interpola(v, x, y):
        if v <= x[0]:
            return y[0]+(y[1]-y[0])/(x[1]-x[0])*(v-x[0])
        elif v >= x[-1]:
            return y[-2]+(y[-1]-y[-2])/(x[-1]-x[-2])*(v-x[-2])
        else:
            f = interp1d(x, y, kind='cubic') 
            return f(v)

Can someone give an example of cosine similarity, in a very simple, graphical way?

Simple JAVA code to calculate cosine similarity

/**
   * Method to calculate cosine similarity of vectors
   * 1 - exactly similar (angle between them is 0)
   * 0 - orthogonal vectors (angle between them is 90)
   * @param vector1 - vector in the form [a1, a2, a3, ..... an]
   * @param vector2 - vector in the form [b1, b2, b3, ..... bn]
   * @return - the cosine similarity of vectors (ranges from 0 to 1)
   */
  private double cosineSimilarity(List<Double> vector1, List<Double> vector2) {

    double dotProduct = 0.0;
    double normA = 0.0;
    double normB = 0.0;
    for (int i = 0; i < vector1.size(); i++) {
      dotProduct += vector1.get(i) * vector2.get(i);
      normA += Math.pow(vector1.get(i), 2);
      normB += Math.pow(vector2.get(i), 2);
    }
    return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
  }

Xcode Error: "The app ID cannot be registered to your development team."

I encountered the same problem when I was trying to compile a sample project provided by Apple. In the end I figured out that apparently they pre-compiled the sample code before shipping them to developers, so the binary had their signature.

The way to solve it is simple, just delete all the built binaries and re-compile using your own bundle identifier and you should be fine.

Just go to the menu bar, click on [Product] -> [Clean Build Folder] to delete all compiled binaries

Clean Build Folder

Delete all rows in table

You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.

See the MySQL 5.1 Reference Manual for the [RENAME TABLE][1] and [CREATE TABLE][2] commands.

RENAME TABLE tbl TO tbl_old;

CREATE TABLE tbl LIKE tbl_old;

DROP TABLE tbl_old; -- at your leisure

This approach can help minimize application downtime.

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

  1. install tomcat

    # yum install tomcat6*

  2. edit tomcat conf file

    # vim /etc/tomcat6/tomcat-users.xml

something like:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
  <user username="TomcatAdmin" password="tomcat" roles="admin,manager"/>
</tomcat-users>
  1. create root directory for your J2EE project, example:

    $ mkdir -p ~/Project/java/

  2. do symbolic link, /usr/share/tomcat6/webapps/ to ~/Project/java/

    # ln -s /home//Project/java//dist/.war /usr/share/tomcat6/webapps/.war

Note: war archive file is created automatcaly when you use netbeans

0r you can do:

# ln -s /home/<login>/Project/java/<myProject>/webapps /usr/share/tomcat6/webapps/<myProject>
  1. check /etc/hosts file, this file must contain the machine name, mine hosts file

    jonathan 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

  2. start httpd service

    # service httpd start

  3. check loclahost web page

  4. start tomcat6

    # service tomcat6 start

  5. check localhost:8080 web page

  6. check that tomcat show your project
    if not:

    • check symbolic link and restart tomcat6 service
    • or add manualy with tomcat manager web page
      a) Set project name
      b) Se path to web.xml file
      c) Valid
      d) start your project (from web page)

for fedora 13 and under they are some problem, how fix it:

# chmod -R g+w /var/log/tomcat6 /etc/tomcat6/Catalina  
# chmod -R g+w /usr/share/tomcat6/work/  

check in log files located in /var/log/tomcat6/ if they are anymore "permission denied" message

Best Practices for securing a REST API / web service

You may also want to take a look at OAuth, an emerging open protocol for token-based authorization specifically targeting http apis.

It is very similar to the approach taken by flickr and remember the milk "rest" apis (not necessarily good examples of restful apis, but good examples of the token-based approach).

How to get http headers in flask?

If any one's trying to fetch all headers that were passed then just simply use:

dict(request.headers)

it gives you all the headers in a dict from which you can actually do whatever ops you want to. In my use case I had to forward all headers to another API since the python API was a proxy

Where to find the win32api module for Python?

I've found that UC Irvine has a great collection of python modules, pywin32 (win32api) being one of many listed there. I'm not sure how they do with keeping up with the latest versions of these modules but it hasn't let me down yet.

UC Irvine Python Extension Repository - http://www.lfd.uci.edu/~gohlke/pythonlibs

pywin32 module - http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

How can I divide two integers to get a double?

You want to cast the numbers:

double num3 = (double)num1/(double)num2;

Note: If any of the arguments in C# is a double, a double divide is used which results in a double. So, the following would work too:

double num3 = (double)num1/num2;

For more information see:

Dot Net Perls

jQuery .ready in a dynamically inserted iframe

Following DrJokepu's and David Murdoch idea I implemented a more complete version. It requires jQuery on both the parent and iframe and the iframe to be in your control.

iframe code:

var iframe = window.frameElement;

if (iframe){
    iframe.contentDocument = document;//normalization: some browsers don't set the contentDocument, only the contentWindow

    var parent = window.parent;
    $(parent.document).ready(function(){//wait for parent to make sure it has jQuery ready
        var parent$ = parent.jQuery;

        parent$(iframe).trigger("iframeloading");

        $(function(){
            parent$(iframe).trigger("iframeready");
        });

        $(window).load(function(){//kind of unnecessary, but here for completion
            parent$(iframe).trigger("iframeloaded");
        });

        $(window).unload(function(e){//not possible to prevent default
            parent$(iframe).trigger("iframeunloaded");
        });

        $(window).on("beforeunload",function(){
            parent$(iframe).trigger("iframebeforeunload");
        });
    });
}

parent test code:

$(function(){
    $("iframe").on("iframeloading iframeready iframeloaded iframebeforeunload iframeunloaded", function(e){
        console.log(e.type);
    });
});

Where to get this Java.exe file for a SQL Developer installation

You must install the latest Java SE Development Kit (note not the Java SE Runtime Environment ) and provide the path ex C:\Program Files\Java\jdk1.6.0_41

Refresh image with a new one at the same url

What I ended up doing was having the server map any request for an image at that directory to the source that I was trying to update. I then had my timer append a number onto the end of the name so the DOM would see it as a new image and load it.

E.g.

http://localhost/image.jpg
//and
http://localhost/image01.jpg

will request the same image generation code but it will look like different images to the browser.

var newImage = new Image();
newImage.src = "http://localhost/image.jpg";
var count = 0;
function updateImage()
{
    if(newImage.complete) {
        document.getElementById("theText").src = newImage.src;
        newImage = new Image();
        newImage.src = "http://localhost/image/id/image" + count++ + ".jpg";
    }
    setTimeout(updateImage, 1000);
}

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

The same issue faced me with XAMPP 7 and opencart Arabic 3. Replacing localhost by the actual machine name reslove the issue.

How to "set a breakpoint in malloc_error_break to debug"

In your screenshot, you didn't specify any module: try setting "libsystem_c.dylib"

enter image description here

I did that, and it works : breakpoint stops here (although the stacktrace often rise from some obscure system lib...)

string sanitizer for filename

$fname = str_replace('/','',$fname);

Since users might use the slash to separate two words it would be better to replace with a dash instead of NULL

How to start Activity in adapter?

When implementing the onClickListener, you can use v.getContext.startActivity.

btn.setOnClickListener(new OnClickListener() {                  
    @Override
    public void onClick(View v) {
        v.getContext().startActivity(PUT_YOUR_INTENT_HERE);
    }
});

Set UITableView content inset permanently

Add in numberOfRowsInSection your code [self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)];. So you will set your contentInset always you reload data in your table

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

To everyone having problems with Newtonsoft.Json v4.5 version try using this in web.config or app.config:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
       <dependentAssembly>
           <assemblyIdentity name="Newtonsoft.Json"
               publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
           <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
       </dependentAssembly>
    </assemblyBinding>
</runtime>

IMPORTANT: Check that the configuration tag of your config file has no namespace attribute (as suggested in https://stackoverflow.com/a/12011221/150370). Otherwise, assemblyBinding tags will be ignored.

Handling the null value from a resultset in JAVA

Since the column may be null in the database, the rs.getString() will throw a NullPointerException()

No.

rs.getString will not throw NullPointer if the column is present in the selected result set (SELECT query columns) For a particular record if value for the 'comumn is null in db, you must do something like this -

String myValue = rs.getString("myColumn");
if (rs.wasNull()) {
    myValue = ""; // set it to empty string as you desire.
}

You may want to refer to wasNull() documentation -

From java.sql.ResultSet
boolean wasNull() throws SQLException;

* Reports whether
* the last column read had a value of SQL <code>NULL</code>.
* Note that you must first call one of the getter methods
* on a column to try to read its value and then call
* the method <code>wasNull</code> to see if the value read was
* SQL <code>NULL</code>.
*
* @return <code>true</code> if the last column value read was SQL
*         <code>NULL</code> and <code>false</code> otherwise
* @exception SQLException if a database access error occurs or this method is 
*            called on a closed result set
*/

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

Go to Project Properties and under Build Make sure that the "Optimize Code" checkbox is unchecked.

Also, set the "Debug Info" dropdown to "Full" in the Advanced Options (Under Build tab).

How can I switch to another branch in git?

Check remote branch list:

git branch -a

Switch to another Branch:

git checkout -b <local branch name> <Remote branch name>
Example: git checkout -b Dev_8.4 remotes/gerrit/Dev_8.4

Check local Branch list:

git branch

Update everything:

git pull

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

How to convert int[] to Integer[] in Java?

Simply use:

public static int[] intArrayToIntegerArray(int[] a) {
    Integer[] b = new Integer[a.length];
    for(int i = 0; i < array.length; i++){
        b[i] = a[i];
    }
    return g;
}

Mythical man month 10 lines per developer day - how close on large projects?

Steve McConnell gives an interesting statistic in his book "Software Estimation" (p62 Table 5.2) He distinguish between project types (Avionic, Business, Telco, etc) and project size 10 kLOC, 100 kLOC, 250 kLOC. The numbers are given for each combination in LOC/StaffMonth. E.G. Avionic: 200, 50, 40 Intranet Systems (Internal): 4000, 800, 600 Embedded Systems: 300, 70, 60

Which means: eg. for Avionic 250-kLOC project there are 40 (LOC/Month) / 22 (Days/Month) == <2LOC/day!

How do function pointers in C work?

Starting from scratch function has Some Memory Address From Where They start executing. In Assembly Language They Are called as (call "function's memory address").Now come back to C If function has a memory address then they can be manipulated by Pointers in C.So By the rules of C

1.First you need to declare a pointer to function 2.Pass the Address of the Desired function

****Note->the functions should be of same type****

This Simple Programme will Illustrate Every Thing.

#include<stdio.h>
void (*print)() ;//Declare a  Function Pointers
void sayhello();//Declare The Function Whose Address is to be passed
                //The Functions should Be of Same Type
int main()
{
 print=sayhello;//Addressof sayhello is assigned to print
 print();//print Does A call To The Function 
 return 0;
}

void sayhello()
{
 printf("\n Hello World");
}

enter image description hereAfter That lets See How machine Understands Them.Glimpse of machine instruction of the above programme in 32 bit architecture.

The red mark area is showing how the address is being exchanged and storing in eax. Then their is a call instruction on eax. eax contains the desired address of the function.

Renaming a directory in C#

One already exists. If you cannot get over the "Move" syntax of the System.IO namespace. There is a static class FileSystem within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory and RenameFile already within it.

As mentioned by SLaks, this is just a wrapper for Directory.Move and File.Move.

Set font-weight using Bootstrap classes

On Bootstrap 4 you can use:

<p class="font-weight-bold">Bold text.</p>
<p class="font-weight-normal">Normal weight text.</p>
<p class="font-weight-light">Light weight text.</p>

Why can't I use background image and color together?

background:url(directoryName/imageName.extention) bottom left no-repeat; 
background-color: red;

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

I use std::string::compare wrapped in utility method like below:

static bool startsWith(const string& s, const string& prefix) {
    return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}

How to select clear table contents without destroying the table?

There is a condition that most of these solutions do not address. I revised Patrick Honorez's solution to handle it. I felt I had to share this because I was pulling my hair out when the original function was occasionally clearing more data that I expected.

The situation happens when the table only has one column and the .SpecialCells(xlCellTypeConstants).ClearContents attempts to clear the contents of the top row. In this situation, only one cell is selected (the top row of the table that only has one column) and the SpecialCells command applies to the entire sheet instead of the selected range. What was happening to me was other cells on the sheet that were outside of my table were also getting cleared.

I did some digging and found this advice from Mathieu Guindon: Range SpecialCells ClearContents clears whole sheet

Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.

Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.

If the list/table only has one column (in row 1), this revision will check to see if the cell has a formula and if not, it will only clear the contents of that one cell.

Public Sub ClearList(lst As ListObject)
'Clears a listObject while leaving 1 empty row + formula
' https://stackoverflow.com/a/53856079/1898524
'
'With special help from this post to handle a single column table.
'   Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
'   Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
' https://stackoverflow.com/questions/40537537/range-specialcells-clearcontents-clears-whole-sheet-instead

    On Error Resume Next
    
    With lst
        '.Range.Worksheet.Activate ' Enable this if you are debugging 
    
        If .ShowAutoFilter Then .AutoFilter.ShowAllData
        If .DataBodyRange.Rows.Count = 1 Then Exit Sub ' Table is already clear
        .DataBodyRange.Offset(1).Rows.Clear
        
        If .DataBodyRange.Columns.Count > 1 Then ' Check to see if SpecialCells is going to evaluate just one cell.
            .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
        ElseIf Not .Range.HasFormula Then
            ' Only one cell in range and it does not contain a formula.
            .DataBodyRange.Rows(1).ClearContents
        End If

        .Resize .Range.Rows("1:2")
        
        .HeaderRowRange.Offset(1).Select

        ' Reset used range on the sheet
        Dim X
        X = .Range.Worksheet.UsedRange.Rows.Count 'see J-Walkenbach tip 73

    End With

End Sub

A final step I included is a tip that is attributed to John Walkenbach, sometimes noted as J-Walkenbach tip 73 Automatically Resetting The Last Cell

Checking if element exists with Python Selenium

A) Yes. The easiest way to check if an element exists is to simply call find_element inside a try/catch.

B) Yes, I always try to identify elements without using their text for 2 reasons:

  1. the text is more likely to change and;
  2. if it is important to you, you won't be able to run your tests against localized builds.

solution either:

  1. You can use xpath to find a parent or ancestor element that has an ID or some other unique identifier and then find it's child/descendant that matches or;
  2. you could request an ID or name or some other unique identifier for the link itself.

For the follow up questions, using try/catch is how you can tell if an element exists or not and good examples of waits can be found here: http://seleniumhq.org/docs/04_webdriver_advanced.html

Syntax error: Illegal return statement in JavaScript

where are you trying to return the value? to console in dev tools is better for debugging

<script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
  if(ask==false){
    return false;     
  } else {
    return true;
  }
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>

How do I compare two columns for equality in SQL Server?

I'd go with the CASE WHEN also.

Depending on what you actually want to do, there may be other options though, like using an outer join or whatever, but that doesn't seem to be what you need in this case.

What does operator "dot" (.) mean?

The dot itself is not an operator, .^ is.

The .^ is a pointwise¹ (i.e. element-wise) power, as .* is the pointwise product.

.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. The sizes of A and B must be the same or be compatible.

C.f.

¹) Hence the dot.

PHP function to build query string from array

Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.

How do I remove/delete a folder that is not empty?

With os.walk I would propose the solution which consists of 3 one-liner Python calls:

python -c "import sys; import os; [os.chmod(os.path.join(rs,d), 0o777) for rs,ds,fs in os.walk(_path_) for d in ds]"
python -c "import sys; import os; [os.chmod(os.path.join(rs,f), 0o777) for rs,ds,fs in os.walk(_path_) for f in fs]"
python -c "import os; import shutil; shutil.rmtree(_path_, ignore_errors=False)"

The first script chmod's all sub-directories, the second script chmod's all files. Then the third script removes everything with no impediments.

I have tested this from the "Shell Script" in a Jenkins job (I did not want to store a new Python script into SCM, that's why searched for a one-line solution) and it worked for Linux and Windows.

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

Microsoft listed the following methods for getting the a View definition: http://technet.microsoft.com/en-us/library/ms175067.aspx


USE AdventureWorks2012;
GO
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('HumanResources.vEmployee'); 
GO

USE AdventureWorks2012; 
GO
SELECT OBJECT_DEFINITION (OBJECT_ID('HumanResources.vEmployee')) 
AS ObjectDefinition; 
GO

EXEC sp_helptext 'HumanResources.vEmployee';

Getting a list of values from a list of dicts

[x['value'] for x in list_of_dicts]

How to insert a line break before an element using CSS

This works for me:

#restart:before {
    content: ' ';
    clear: right;
    display: block;
}

Confused about __str__ on list in Python

Answer to the question

As pointed out in another answer and as you can read in PEP 3140, str on a list calls for each item __repr__. There is not much you can do about that part.

If you implement __repr__, you will get something more descriptive, but if implemented correctly, not exactly what you expected.

Proper implementation

The fast, but wrong solution is to alias __repr__ to __str__.

__repr__ should not be set to __str__ unconditionally. __repr__ should create a representation, that should look like a valid Python expression that could be used to recreate an object with the same value. In this case, this would rather be Node(2) than 2.

A proper implementation of __repr__ makes it possible to recreate the object. In this example, it should also contain the other significant members, like neighours and distance.

An incomplete example:

class Node:

    def __init__(self, id, neighbours=[], distance=0):
        self.id = id
        self.neighbours = neighbours
        self.distance = distance


    def __str__(self):
        return str(self.id)


    def __repr__(self):
        return "Node(id={0.id}, neighbours={0.neighbours!r}, distance={0.distance})".format(self)
        # in an elaborate implementation, members that have the default
        # value could be left out, but this would hide some information


uno = Node(1)    
due = Node(2)    
tri = Node(3)    
qua = Node(4)

print uno
print str(uno)
print repr(uno)

uno.neighbours.append([[due, 4], [tri, 5]])

print uno
print uno.neighbours
print repr(uno)

Note: print repr(uno) together with a proper implementation of __eq__ and __ne__ or __cmp__ would allow to recreate the object and check for equality.

HTML img align="middle" doesn't align an image

The attribute align=middle sets vertical alignment. To set horizontal alignment using HTML, you can wrap the element inside a center element and remove all the CSS you have now.

_x000D_
_x000D_
<center><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></center>
_x000D_
_x000D_
_x000D_

If you would rather do it in CSS, there are several ways. A simple one is to set text-align on a container:

_x000D_
_x000D_
<div style="text-align: center"><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></div>
_x000D_
_x000D_
_x000D_

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

Pass an array of integers to ASP.NET Web API?

Or you could just pass a string of delimited items and put it into an array or list on the receiving end.

How to do a recursive find/replace of a string with awk or sed?

#!/usr/local/bin/bash -x

find * /home/www -type f | while read files
do

sedtest=$(sed -n '/^/,/$/p' "${files}" | sed -n '/subdomainA/p')

    if [ "${sedtest}" ]
    then
    sed s'/subdomainA/subdomainB/'g "${files}" > "${files}".tmp
    mv "${files}".tmp "${files}"
    fi

done

Center div on the middle of screen

Try this:

 div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
    background: red;
}

Here div is html tag. You wrote a html tag followed by a dot that is wrong.Only a class is written followed by dot.

How to detect if URL has changed after hash in JavaScript

use this code

window.onhashchange = function() { 
     //code  
}

with jQuery

$(window).bind('hashchange', function() {
     //code
});