Programs & Examples On #Enum flags

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

Rails: Using greater than/less than with a where statement

I've only tested this in Rails 4 but there's an interesting way to use a range with a where hash to get this behavior.

User.where(id: 201..Float::INFINITY)

will generate the SQL

SELECT `users`.* FROM `users`  WHERE (`users`.`id` >= 201)

The same can be done for less than with -Float::INFINITY.

I just posted a similar question asking about doing this with dates here on SO.

>= vs >

To avoid people having to dig through and follow the comments conversation here are the highlights.

The method above only generates a >= query and not a >. There are many ways to handle this alternative.

For discrete numbers

You can use a number_you_want + 1 strategy like above where I'm interested in Users with id > 200 but actually look for id >= 201. This is fine for integers and numbers where you can increment by a single unit of interest.

If you have the number extracted into a well named constant this may be the easiest to read and understand at a glance.

Inverted logic

We can use the fact that x > y == !(x <= y) and use the where not chain.

User.where.not(id: -Float::INFINITY..200)

which generates the SQL

SELECT `users`.* FROM `users` WHERE (NOT (`users`.`id` <= 200))

This takes an extra second to read and reason about but will work for non discrete values or columns where you can't use the + 1 strategy.

Arel table

If you want to get fancy you can make use of the Arel::Table.

User.where(User.arel_table[:id].gt(200))

will generate the SQL

"SELECT `users`.* FROM `users` WHERE (`users`.`id` > 200)"

The specifics are as follows:

User.arel_table              #=> an Arel::Table instance for the User model / users table
User.arel_table[:id]         #=> an Arel::Attributes::Attribute for the id column
User.arel_table[:id].gt(200) #=> an Arel::Nodes::GreaterThan which can be passed to `where`

This approach will get you the exact SQL you're interested in however not many people use the Arel table directly and can find it messy and/or confusing. You and your team will know what's best for you.

Bonus

Starting in Rails 5 you can also do this with dates!

User.where(created_at: 3.days.ago..DateTime::Infinity.new)

will generate the SQL

SELECT `users`.* FROM `users` WHERE (`users`.`created_at` >= '2018-07-07 17:00:51')

Double Bonus

Once Ruby 2.6 is released (December 25, 2018) you'll be able to use the new infinite range syntax! Instead of 201..Float::INFINITY you'll be able to just write 201... More info in this blog post.

Selecting Values from Oracle Table Variable / Array?

In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.

So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:

CREATE OR REPLACE TYPE array is table of number;
/

Then you can use it as in these two examples within PL/SQL:

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    for i in (select level from dual connect by level < 10) loop
  5      p.extend;
  6      p(p.count) := i.level;
  7    end loop;
  8    for x in (select column_value from table(cast(p as array))) loop
  9       dbms_output.put_line(x.column_value);
 10    end loop;
 11* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    select level bulk collect into p from dual connect by level < 10;
  5    for x in (select column_value from table(cast(p as array))) loop
  6       dbms_output.put_line(x.column_value);
  7    end loop;
  8* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

Additional example based on comments

Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.

CREATE OR REPLACE PACKAGE p_cache AS
  FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;
/

CREATE OR REPLACE PACKAGE BODY p_cache AS

  cache_array  array;

  FUNCTION get_p_cursor RETURN sys_refcursor IS
    pCursor  sys_refcursor;
  BEGIN
    OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
    RETURN pCursor;
  END get_p_cursor;

  -- Package initialization runs once in each session that references the package
  BEGIN
    SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
  END p_cache;
/

How to do HTTP authentication in android?

For my Android projects I've used the Base64 library from here:

http://iharder.net/base64

It's a very extensive library and so far I've had no problems with it.

jquery simple image slideshow tutorial

Here is my adaptation of Michael Soriano's tutorial. See below or in JSBin.

_x000D_
_x000D_
$(function() {_x000D_
  var theImage = $('ul#ss li img');_x000D_
  var theWidth = theImage.width();_x000D_
  //wrap into mother div_x000D_
  $('ul#ss').wrap('<div id="mother" />');_x000D_
  //assign height width and overflow hidden to mother_x000D_
  $('#mother').css({_x000D_
    width: function() {_x000D_
      return theWidth;_x000D_
    },_x000D_
    height: function() {_x000D_
      return theImage.height();_x000D_
    },_x000D_
    position: 'relative',_x000D_
    overflow: 'hidden'_x000D_
  });_x000D_
  //get total of image sizes and set as width for ul _x000D_
  var totalWidth = theImage.length * theWidth;_x000D_
  $('ul').css({_x000D_
    width: function() {_x000D_
      return totalWidth;_x000D_
    }_x000D_
  });_x000D_
_x000D_
  var ss_timer = setInterval(function() {_x000D_
    ss_next();_x000D_
  }, 3000);_x000D_
_x000D_
  function ss_next() {_x000D_
    var a = $(".active");_x000D_
    a.removeClass('active');_x000D_
_x000D_
    if (a.hasClass('last')) {_x000D_
      //last element -- loop_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (0)_x000D_
      }, 1000);_x000D_
      a.siblings(":first").addClass('active');_x000D_
    } else {_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (-(a.index() + 1) * theWidth)_x000D_
      }, 1000);_x000D_
      a.next().addClass('active');_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Cancel slideshow and move next manually on click_x000D_
  $('ul#ss li img').on('click', function() {_x000D_
    clearInterval(ss_timer);_x000D_
    ss_next();_x000D_
  });_x000D_
_x000D_
});
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
#ss {_x000D_
  list-style: none;_x000D_
}_x000D_
#ss li {_x000D_
  float: left;_x000D_
}_x000D_
#ss img {_x000D_
  width: 200px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<ul id="ss">_x000D_
  <li class="active">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado-colors.jpg">_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/monte-vista.jpg">_x000D_
  </li>_x000D_
  <li class="last">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado.jpg">_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How do I get the coordinate position after using jQuery drag and drop?

Had the same problem. My solution is next:

$("#element").droppable({
    drop: function( event, ui ) {

        // position of the draggable minus position of the droppable
        // relative to the document
        var $newPosX = ui.offset.left - $(this).offset().left;
        var $newPosY = ui.offset.top - $(this).offset().top;

    }
});

Best way to script remote SSH commands in Batch (Windows)

As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run

Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.

Then you can create an ssh batch script such as

ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.

SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF

REM ------------------------------
REM SSH Server details
REM ------------------------------

:WEB1
CLS
call ssh [email protected]
cmd /k

:WEB2
CLS
call ssh [email protected]
cmd /k

How do I update a GitHub forked repository?

Assuming your fork is https://github.com/me/foobar and original repository is https://github.com/someone/foobar

  1. Visit https://github.com/me/foobar/compare/master...someone:master

  2. If you see green text Able to merge then press Create pull request

  3. On the next page, scroll to the bottom of the page and click Merge pull request and Confirm merge.

Check if a string is not NULL or EMPTY

I would define $Version as a string to start with

[string]$Version

and if it's a param you can use the code posted by Samselvaprabu or if you would rather not present your users with an error you can do something like

while (-not($version)){
    $version = Read-Host "Enter the version ya fool!"
}
$request += "/" + $version

How do you make a HTTP request with C++?

With this answer I refer to the answer from Software_Developer. By rebuilding the code I found that some parts are deprecated (gethostbyname()) or do not provide error handling (creation of sockets, sending something) for an operation.

The following windows code is tested with Visual Studio 2013 and Windows 8.1 64-bit as well as Windows 7 64-bit. It will target an IPv4 TCP Connection with the Web Server of www.google.com.

#include <winsock2.h>
#include <WS2tcpip.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
    int main (){
    // Initialize Dependencies to the Windows Socket.
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        cout << "WSAStartup failed.\n";
        system("pause");
        return -1;
    }

    // We first prepare some "hints" for the "getaddrinfo" function
    // to tell it, that we are looking for a IPv4 TCP Connection.
    struct addrinfo hints;
    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;          // We are targeting IPv4
    hints.ai_protocol = IPPROTO_TCP;    // We are targeting TCP
    hints.ai_socktype = SOCK_STREAM;    // We are targeting TCP so its SOCK_STREAM

    // Aquiring of the IPv4 address of a host using the newer
    // "getaddrinfo" function which outdated "gethostbyname".
    // It will search for IPv4 addresses using the TCP-Protocol.
    struct addrinfo* targetAdressInfo = NULL;
    DWORD getAddrRes = getaddrinfo("www.google.com", NULL, &hints, &targetAdressInfo);
    if (getAddrRes != 0 || targetAdressInfo == NULL)
    {
        cout << "Could not resolve the Host Name" << endl;
        system("pause");
        WSACleanup();
        return -1;
    }

    // Create the Socket Address Informations, using IPv4
    // We dont have to take care of sin_zero, it is only used to extend the length of SOCKADDR_IN to the size of SOCKADDR
    SOCKADDR_IN sockAddr;
    sockAddr.sin_addr = ((struct sockaddr_in*) targetAdressInfo->ai_addr)->sin_addr;    // The IPv4 Address from the Address Resolution Result
    sockAddr.sin_family = AF_INET;  // IPv4
    sockAddr.sin_port = htons(80);  // HTTP Port: 80

    // We have to free the Address-Information from getaddrinfo again
    freeaddrinfo(targetAdressInfo);

    // Creation of a socket for the communication with the Web Server,
    // using IPv4 and the TCP-Protocol
    SOCKET webSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (webSocket == INVALID_SOCKET)
    {
        cout << "Creation of the Socket Failed" << endl;
        system("pause");
        WSACleanup();
        return -1;
    }

    // Establishing a connection to the web Socket
    cout << "Connecting...\n";
    if(connect(webSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr)) != 0)
    {
        cout << "Could not connect";
        system("pause");
        closesocket(webSocket);
        WSACleanup();
        return -1;
    }
    cout << "Connected.\n";

    // Sending a HTTP-GET-Request to the Web Server
    const char* httpRequest = "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n";
    int sentBytes = send(webSocket, httpRequest, strlen(httpRequest),0);
    if (sentBytes < strlen(httpRequest) || sentBytes == SOCKET_ERROR)
    {
        cout << "Could not send the request to the Server" << endl;
        system("pause");
        closesocket(webSocket);
        WSACleanup();
        return -1;
    }

    // Receiving and Displaying an answer from the Web Server
    char buffer[10000];
    ZeroMemory(buffer, sizeof(buffer));
    int dataLen;
    while ((dataLen = recv(webSocket, buffer, sizeof(buffer), 0) > 0))
    {
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            cout << buffer[i];
            i += 1;
        }
    }

    // Cleaning up Windows Socket Dependencies
    closesocket(webSocket);
    WSACleanup();

    system("pause");
    return 0;
}

References:

Deprecation of gethostbyname

Return Value of socket()

Return Value of send()

How to edit .csproj file

There is an easier way so you don't have to unload the project. Just install this tool called EditProj in Visual Studio:
https://marketplace.visualstudio.com/items?itemName=EdMunoz.EditProj

Then right click edit you will have a new menu item Edit Project File :)
enter image description here

How to escape a JSON string to have it in a URL?

I was looking to do the same thing. problem for me was my url was getting way too long. I found a solution today using Bruno Jouhier's jsUrl.js library.

I haven't tested it very thoroughly yet. However, here is an example showing character lengths of the string output after encoding the same large object using 3 different methods:

  • 2651 characters using jQuery.param
  • 1691 characters using JSON.stringify + encodeURIComponent
  • 821 characters using JSURL.stringify

clearly JSURL has the most optimized format for urlEncoding a js object.

the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q shows benchmarks for encoding and parsing.

Note: After testing, it looks like jsurl.js library uses ECMAScript 5 functions such as Object.keys, Array.map, and Array.filter. Therefore, it will only work on modern browsers (no ie 8 and under). However, are polyfills for these functions that would make it compatible with more browsers.

install beautiful soup using pip

The easy method that will work even in corrupted setup environment is :

To download ez_setup.py and run it using command line

python ez_setup.py

output

Extracting in c:\uu\uu\appdata\local\temp\tmpjxvil3 Now working in c:\u\u\appdata\local\temp\tmpjxvil3\setuptools-5.6 Installing Setuptools

run

pip install beautifulsoup4

output

Downloading/unpacking beautifulsoup4 Running setup.py ... egg_info for package Installing collected packages: beautifulsoup4 Running setup.py install for beautifulsoup4 Successfully installed beautifulsoup4 Cleaning up...

Bam ! |Done¬

How to overlay one div over another div

This is what you need:

_x000D_
_x000D_
function showFrontLayer() {_x000D_
  document.getElementById('bg_mask').style.visibility='visible';_x000D_
  document.getElementById('frontlayer').style.visibility='visible';_x000D_
}_x000D_
function hideFrontLayer() {_x000D_
  document.getElementById('bg_mask').style.visibility='hidden';_x000D_
  document.getElementById('frontlayer').style.visibility='hidden';_x000D_
}
_x000D_
#bg_mask {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: auto;_x000D_
  margin-top: 0px;_x000D_
  width: 981px;_x000D_
  height: 610px;_x000D_
  background : url("img_dot_white.jpg") center;_x000D_
  z-index: 0;_x000D_
  visibility: hidden;_x000D_
} _x000D_
_x000D_
#frontlayer {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: 70px 140px 175px 140px;_x000D_
  padding : 30px;_x000D_
  width: 700px;_x000D_
  height: 400px;_x000D_
  background-color: orange;_x000D_
  visibility: hidden;_x000D_
  border: 1px solid black;_x000D_
  z-index: 1;_x000D_
} _x000D_
_x000D_
_x000D_
</style>
_x000D_
<html>_x000D_
  <head>_x000D_
    <META HTTP-EQUIV="EXPIRES" CONTENT="-1" />_x000D_
_x000D_
  </head>_x000D_
  <body>_x000D_
    <form action="test.html">_x000D_
      <div id="baselayer">_x000D_
_x000D_
        <input type="text" value="testing text"/>_x000D_
        <input type="button" value="Show front layer" onclick="showFrontLayer();"/> Click 'Show front layer' button<br/><br/><br/>_x000D_
_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing textsting text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        <div id="bg_mask">_x000D_
          <div id="frontlayer"><br/><br/>_x000D_
            Now try to click on "Show front layer" button or the text box. It is not active.<br/><br/><br/>_x000D_
            Use position: absolute to get the one div on top of another div.<br/><br/><br/>_x000D_
            The bg_mask div is between baselayer and front layer.<br/><br/><br/>_x000D_
            In bg_mask, img_dot_white.jpg(1 pixel in width and height) is used as background image to avoid IE browser transparency issue;<br/><br/><br/>_x000D_
            <input type="button" value="Hide front layer" onclick="hideFrontLayer();"/>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </form>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Get year, month or day from numpy datetime64

I find the following tricks give between 2x and 4x speed increase versus the pandas method described above (i.e. pd.DatetimeIndex(dates).year etc.). The speed of [dt.year for dt in dates.astype(object)] I find to be similar to the pandas method. Also these tricks can be applied directly to ndarrays of any shape (2D, 3D etc.)

dates = np.arange(np.datetime64('2000-01-01'), np.datetime64('2010-01-01'))
years = dates.astype('datetime64[Y]').astype(int) + 1970
months = dates.astype('datetime64[M]').astype(int) % 12 + 1
days = dates - dates.astype('datetime64[M]') + 1

ipython notebook clear cell output in code

You can use the IPython.display.clear_output to clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print(i, flush=True)

System.Drawing.Image to stream C#

Use a memory stream

using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ...);
    return ms.ToArray();
}

How can I disable the bootstrap hover color for links?

Mark color: #005580; as color: #005580 !important;.

It will override default bootstrap hover.

Firebase onMessageReceived not called when app in background

There are two types of messages: notification messages and data messages. If you only send data message, that is without notification object in your message string. It would be invoked when your app in background.

Redis: Show database size/size for keys

How about redis-cli get KEYNAME | wc -c

Catch Ctrl-C in C

Or you can put the terminal in raw mode, like this:

struct termios term;

term.c_iflag |= IGNBRK;
term.c_iflag &= ~(INLCR | ICRNL | IXON | IXOFF);
term.c_lflag &= ~(ICANON | ECHO | ECHOK | ECHOE | ECHONL | ISIG | IEXTEN);
term.c_cc[VMIN] = 1;
term.c_cc[VTIME] = 0;
tcsetattr(fileno(stdin), TCSANOW, &term);

Now it should be possible to read Ctrl+C keystrokes using fgetc(stdin). Beware using this though because you can't Ctrl+Z, Ctrl+Q, Ctrl+S, etc. like normally any more either.

How to programmatically set drawableLeft on Android button?

Kotlin Version

Use below snippet to add a drawable left to the button:

val drawable = ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_16dp)
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)

.

Important Point in Using Android Vector Drawable

When you are using an android vector drawable and want to have backward compatibility for API below 21, add the following codes to:

In app level build.gradle:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

In Application class:

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    }

}

How to iterate std::set?

Another example for the C++11 standard:

set<int> data;
data.insert(4);
data.insert(5);

for (const int &number : data)
  cout << number;

How to mention C:\Program Files in batchfile

While createting the bat file, you can easly avoid the space. If you want to mentioned "program files "folder in batch file.

Do following steps:

1. Type c: then press enter

2. cd program files

3. cd "choose your own folder name"

then continue as you wish.

This way you can create batch file and you can mention program files folder.

Plotting categorical data with pandas and matplotlib

You can simply use value_counts with sort option set to False. This will preserve ordering of the categories

df['colour'].value_counts(sort=False).plot.bar(rot=0)

link to image

SQL Server 2012 Install or add Full-text search

You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)

Directions:

  1. Open the Programs and Features control panel.
  2. Select Microsoft SQL Server 2012 and click Change.
  3. When prompted to Add/Repair/Remove, select Add.
  4. Advance through the wizard until the Feature Selection screen. Then select Full-Text Search.

Step 1 Step 2

enter image description here

  1. On the Installation Type screen, select the appropriate SQL Server instance.

  2. Advance through the rest of the wizard.

Source (with screenshots): http://www.techrepublic.com/blog/networking/adding-sql-full-text-search-to-an-existing-sql-server/5546

Creating a new ArrayList in Java

If you just want a list:

ArrayList<Class> myList = new ArrayList<Class>();

If you want an arraylist of a certain length (in this case size 10):

List<Class> myList = new ArrayList<Class>(10);

If you want to program against the interfaces (better for abstractions reasons):

List<Class> myList = new ArrayList<Class>();

Programming against interfaces is considered better because it's more abstract. You can change your Arraylist with a different list implementation (like a LinkedList) and the rest of your application doesn't need any changes.

Call to undefined function oci_connect()

Download from Instant Client for Microsoft Windows (x64) and extract the files below to "c:\oracle":

instantclient-basic-windows.x64-12.1.0.2.0.zip

instantclient-sqlplus-windows.x64-12.1.0.2.0.zip

instantclient-sdk-windows.x64-12.1.0.2.0.zip This will create the following folder "C:\Oracle\instantclient_12_1".

Finally, add the "C:\Oracle\instantclient_12_1" folder to the PATH enviroment variable, placing it on the leftmost place.

Then Restart your server.

How do you add an action to a button programmatically in xcode

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(aMethod1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];   

How to access SOAP services from iPhone

My solution was to have a proxy server accept REST, issue the SOAP request, and return result, using PHP.

Time to implement: 15-30 minutes.

Not most elegant, but solid.

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: intent.putExtra("key", value);

Eg: intent.putExtra("full_name", "Vishnu Sivan");

Intent intent=getIntent() : It gets the Intent from the previous activity.

fullname = intent.getStringExtra(“full_name”) : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);

How can I check if a single character appears in a string?

To check if something does not exist in a string, you at least need to look at each character in a string. So even if you don't explicitly use a loop, it'll have the same efficiency. That being said, you can try using str.contains(""+char).

Using floats with sprintf() in embedded C

Look in the documentation for sprintf for your platform. Its usually %f or %e. The only place you will find a definite answer is the documentation... if its undocumented all you can do then is contact the supplier.

What platform is it? Someone might already know where the docs are... :)

Why does javascript map function return undefined?

var arr = ['a','b',1];
 var results = arr.filter(function(item){
                if(typeof item ==='string'){return item;}  
               });

Using DISTINCT along with GROUP BY in SQL Server

Perhaps not in the context that you have it, but you could use

SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA

You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.

Building and running app via Gradle and Android Studio is slower than via Eclipse

You can ignore gradle update-to-date checks.

enter image description here

For Windows running Android Studio 1.5: Go to File -> Settings -> Build, Execution, Deployment -> Build tools -> Gradle -> Check Offline work (as shown in image)

down from ~30+ sec to ~3 sec

How to force a web browser NOT to cache images

Simple fix: Attach a random query string to the image:

<img src="foo.cgi?random=323527528432525.24234" alt="">

What the HTTP RFC says:

Cache-Control: no-cache

But that doesn't work that well :)

Any reason not to use '+' to concatenate two strings?

''.join([a, b]) is better solution than +.

Because Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such)

form a += b or a = a + b is fragile even in CPython and isn't present at all in implementations that don't use refcounting (reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource)

https://www.python.org/dev/peps/pep-0008/#programming-recommendations

How to get a div to resize its height to fit container?

You probably are going to want to use the following declaration:

height: 100%;

This will set the div's height to 100% of its containers height, which will make it fill the parent div.

Killing a process created with Python's subprocess.Popen()

In your code it should be

proc1.kill()

Both kill or terminate are methods of the Popen object which sends the signal signal.SIGKILL to the process.

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

Count characters in textarea

$(document).ready(function() {
    var count = $("h1").text().length;
    alert(count);
});

Also, you can put your own element id or class instead of "h1" and length event count your characters of text area string ?

How to output a multiline string in Bash?

Here documents are often used for this purpose.

cat << EOF
usage: up [--level <n>| -n <levels>][--help][--version]

Report bugs to: 
up home page:
EOF

They are supported in all Bourne-derived shells including all versions of Bash.

How to get the name of the current Windows user in JavaScript

If the script is running on Microsoft Windows in an HTA or similar, you can do this:

var wshshell=new ActiveXObject("wscript.shell");
var username=wshshell.ExpandEnvironmentStrings("%username%");

Otherwise, as others have pointed out, you're out of luck. This is considered to be private information and is not provided by the browser to the javascript engine.

Hadoop/Hive : Loading data from .csv on a local machine

if you have a hive setup you can put the local dataset directly using Hive load command in hdfs/s3.

You will need to use "Local" keyword when writing your load command.

Syntax for hiveload command

LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]

Refer below link for more detailed information. https://cwiki.apache.org/confluence/display/Hive/LanguageManual%20DML#LanguageManualDML-Loadingfilesintotables

Get the (last part of) current directory name in C#

You can also use the Uri class.

new Uri("file:///Users/smcho/filegen_from_directory/AIRPassthrough").Segments.Last()

You may prefer to use this class if you want to get some other segment, or if you want to do the same thing with a web address.

Wait until all jQuery Ajax requests are done?

$.when doesn't work for me, callback(x) instead of return x worked as described here: https://stackoverflow.com/a/13455253/10357604

How to format column to number format in Excel sheet?

Sorry to bump an old question but the answer is to count the character length of the cell and not its value.

CellCount = Cells(Row, 10).Value
If Len(CellCount) <= "13" Then
'do something
End If

hope that helps. Cheers

How to delete columns in pyspark dataframe

You can delete column like this:

df.drop("column Name).columns

In your case :

df.drop("id").columns

If you want to drop more than one column you can do:

dfWithLongColName.drop("ORIGIN_COUNTRY_NAME", "DEST_COUNTRY_NAME")

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

Old answer (applicable till 2016)

Here's an Apple developer link that explicitly says that -

on iPhone and iPod touch, which are small screen devices, "Video is NOT presented within the Web Page"

Safari Device-Specific Considerations

Your options:

  • The webkit-playsinline attribute works for HTML5 videos on iOS but only when you save the webpage to your home screen as a webapp - Not if opened a page in Safari
  • For a native app with a WebView (or a hybrid app with HTML, CSS, JS) the UIWebView allows to play the video inline, but only if you set the allowsInlineMediaPlayback property for the UIWebView class to true

How do I change the default schema in sql developer?

Just create a new connection (hit the green plus sign) and enter the schema name and password of the new default schema your DBA suggested. You can switch between your old schema and the new schema with the pull down menu at the top right end of your window.

How to increase the max connections in postgres?

change max_connections variable in postgresql.conf file located in /var/lib/pgsql/data or /usr/local/pgsql/data/

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

PostgreSQL column 'foo' does not exist

You accidentally created the column name with a trailing space and presumably phpPGadmin created the column name with double quotes around it:

create table your_table (
    "foo " -- ...
)

That would give you a column that looked like it was called foo everywhere but you'd have to double quote it and include the space whenever you use it:

select ... from your_table where "foo " is not null

The best practice is to use lower case unquoted column names with PostgreSQL. There should be a setting in phpPGadmin somewhere that will tell it to not quote identifiers (such as table and column names) but alas, I don't use phpPGadmin so I don't where that setting is (or even if it exists).

How to convert an integer to a string in any base?

"{0:b}".format(100) # bin: 1100100
"{0:x}".format(100) # hex: 64
"{0:o}".format(100) # oct: 144

Python: tf-idf-cosine: to find document similarity

First off, if you want to extract count features and apply TF-IDF normalization and row-wise euclidean normalization you can do it in one operation with TfidfVectorizer:

>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> from sklearn.datasets import fetch_20newsgroups
>>> twenty = fetch_20newsgroups()

>>> tfidf = TfidfVectorizer().fit_transform(twenty.data)
>>> tfidf
<11314x130088 sparse matrix of type '<type 'numpy.float64'>'
    with 1787553 stored elements in Compressed Sparse Row format>

Now to find the cosine distances of one document (e.g. the first in the dataset) and all of the others you just need to compute the dot products of the first vector with all of the others as the tfidf vectors are already row-normalized.

As explained by Chris Clark in comments and here Cosine Similarity does not take into account the magnitude of the vectors. Row-normalised have a magnitude of 1 and so the Linear Kernel is sufficient to calculate the similarity values.

The scipy sparse matrix API is a bit weird (not as flexible as dense N-dimensional numpy arrays). To get the first vector you need to slice the matrix row-wise to get a submatrix with a single row:

>>> tfidf[0:1]
<1x130088 sparse matrix of type '<type 'numpy.float64'>'
    with 89 stored elements in Compressed Sparse Row format>

scikit-learn already provides pairwise metrics (a.k.a. kernels in machine learning parlance) that work for both dense and sparse representations of vector collections. In this case we need a dot product that is also known as the linear kernel:

>>> from sklearn.metrics.pairwise import linear_kernel
>>> cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten()
>>> cosine_similarities
array([ 1.        ,  0.04405952,  0.11016969, ...,  0.04433602,
    0.04457106,  0.03293218])

Hence to find the top 5 related documents, we can use argsort and some negative array slicing (most related documents have highest cosine similarity values, hence at the end of the sorted indices array):

>>> related_docs_indices = cosine_similarities.argsort()[:-5:-1]
>>> related_docs_indices
array([    0,   958, 10576,  3277])
>>> cosine_similarities[related_docs_indices]
array([ 1.        ,  0.54967926,  0.32902194,  0.2825788 ])

The first result is a sanity check: we find the query document as the most similar document with a cosine similarity score of 1 which has the following text:

>>> print twenty.data[0]
From: [email protected] (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15

 I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.

Thanks,
- IL
   ---- brought to you by your neighborhood Lerxst ----

The second most similar document is a reply that quotes the original message hence has many common words:

>>> print twenty.data[958]
From: [email protected] (Robert Seymour)
Subject: Re: WHAT car is this!?
Article-I.D.: reed.1993Apr21.032905.29286
Reply-To: [email protected]
Organization: Reed College, Portland, OR
Lines: 26

In article <[email protected]> [email protected] (where's my
thing) writes:
>
>  I was wondering if anyone out there could enlighten me on this car I saw
> the other day. It was a 2-door sports car, looked to be from the late 60s/
> early 70s. It was called a Bricklin. The doors were really small. In
addition,
> the front bumper was separate from the rest of the body. This is
> all I know. If anyone can tellme a model name, engine specs, years
> of production, where this car is made, history, or whatever info you
> have on this funky looking car, please e-mail.

Bricklins were manufactured in the 70s with engines from Ford. They are rather
odd looking with the encased front bumper. There aren't a lot of them around,
but Hemmings (Motor News) ususally has ten or so listed. Basically, they are a
performance Ford with new styling slapped on top.

>    ---- brought to you by your neighborhood Lerxst ----

Rush fan?

--
Robert Seymour              [email protected]
Physics and Philosophy, Reed College    (NeXTmail accepted)
Artificial Life Project         Reed College
Reed Solar Energy Project (SolTrain)    Portland, OR

Android getText from EditText field

EditText txt = (EditText)findviewbyid(R.id.txt);

Editable str = txt.getText().toString();

Toast toast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG);  

toast.show();

C# ListView Column Width Auto

If you have ListView in any Parent panel (ListView dock fill), you can use simply method...

private void ListViewHeaderWidth() {
        int HeaderWidth = (listViewInfo.Parent.Width - 2) / listViewInfo.Columns.Count;
        foreach (ColumnHeader header in listViewInfo.Columns)
        {
            header.Width = HeaderWidth;
        }
    }

What are the "standard unambiguous date" formats for string-to-date conversion in R?

Converting the date without specifying the current format can bring this error to you easily.

Here is an example:

sdate <- "2015.10.10"

Convert without specifying the Format:

date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".

Convert with specified Format:

date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.

CSS Animation and Display None

When animating height (from 0 to auto), using transform: scaleY(0); is another useful approach to hide the element, instead of display: none;:

.section {
  overflow: hidden;
  transition: transform 0.3s ease-out;
  height: auto;
  transform: scaleY(1);
  transform-origin: top;

  &.hidden {
    transform: scaleY(0);
  }
}

JavaScript CSS how to add and remove multiple CSS classes to an element

  addClass(element, className1, className2){
    element.classList.add(className1, className2);
  }
  removeClass(element, className1, className2) {
    element.classList.remove(className1, className2);
  }

removeClass(myElement, 'myClass1', 'myClass2');
addClass(myElement, 'myClass1', 'myClass2');

What is the difference between an int and an Integer in Java and C#?

Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:

Integer i = new Integer(6);

You could call some method on i:

String s = i.toString();//sets s the string representation of i

Whereas with an int:

int i = 6;

You cannot call any methods on it, because it is simply a primitive. So:

String s = i.toString();//will not work!!!

would produce an error, because int is not an object.

int is one of the few primitives in Java (along with char and some others). I'm not 100% sure, but I'm thinking that the Integer object more or less just has an int property and a whole bunch of methods to interact with that property (like the toString() method for example). So Integer is a fancy way to work with an int (Just as perhaps String is a fancy way to work with a group of chars).

I know that Java isn't C, but since I've never programmed in C this is the closest I could come to the answer. Hope this helps!

Integer object javadoc

Integer Ojbect vs. int primitive comparison

How to refresh token with Google API client?

Sometimes Refresh Token i not generated by using $client->setAccessType ("offline");.

Try this:

$client->setAccessType ("offline");
$client->setApprovalPrompt ("force"); 

How to decode a QR-code image in (preferably pure) Python?

For Windows using ZBar

Pre-requisites:

To decode:

from PIL import Image
from pyzbar import pyzbar

img = Image.open('My-Image.jpg')
output = pyzbar.decode(img)
print(output)

Alternatively, you can also try using ZBarLight by setting it up as mentioned here:
https://pypi.org/project/zbarlight/

Where do I find old versions of Android NDK?

Simply replacing .bin with .tar.bz2 is not enough, for NDK releases older than 10b. For example, https://dl.google.com/android/ndk/android-ndk-r10b-linux-x86_64.tar.bz2 is not a valid link.

Turned out that the correct link for 10b was: https://dl.google.com/android/ndk/android-ndk32-r10b-linux-x86_64.tar.bz2 (note the additional '32'). However, this doesn't seem to apply to e.g. 10a, as this link doesn't work: https://dl.google.com/android/ndk/android-ndk32-r10a-linux-x86_64.tar.bz2 .

Bottom line: use http://web.archive.org until Google fixes this, if ever...

How to get the return value from a thread in python?

One way I've seen is to pass a mutable object, such as a list or a dictionary, to the thread's constructor, along with a an index or other identifier of some sort. The thread can then store its results in its dedicated slot in that object. For example:

def foo(bar, result, index):
    print 'hello {0}'.format(bar)
    result[index] = "foo"

from threading import Thread

threads = [None] * 10
results = [None] * 10

for i in range(len(threads)):
    threads[i] = Thread(target=foo, args=('world!', results, i))
    threads[i].start()

# do some other stuff

for i in range(len(threads)):
    threads[i].join()

print " ".join(results)  # what sound does a metasyntactic locomotive make?

If you really want join() to return the return value of the called function, you can do this with a Thread subclass like the following:

from threading import Thread

def foo(bar):
    print 'hello {0}'.format(bar)
    return "foo"

class ThreadWithReturnValue(Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs={}, Verbose=None):
        Thread.__init__(self, group, target, name, args, kwargs, Verbose)
        self._return = None
    def run(self):
        if self._Thread__target is not None:
            self._return = self._Thread__target(*self._Thread__args,
                                                **self._Thread__kwargs)
    def join(self):
        Thread.join(self)
        return self._return

twrv = ThreadWithReturnValue(target=foo, args=('world!',))

twrv.start()
print twrv.join()   # prints foo

That gets a little hairy because of some name mangling, and it accesses "private" data structures that are specific to Thread implementation... but it works.

For python3

class ThreadWithReturnValue(Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs={}, Verbose=None):
        Thread.__init__(self, group, target, name, args, kwargs)
        self._return = None
    def run(self):
        print(type(self._target))
        if self._target is not None:
            self._return = self._target(*self._args,
                                                **self._kwargs)
    def join(self, *args):
        Thread.join(self, *args)
        return self._return

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

I got a solution after a long time in tutorials.

I followed the github tutorial on this link -> https://help.github.com/articles/error-permission-denied-publickey and I was able to connect in every step. But when I was trying to git push -u origin master I got this error:

Permission denied (publickey). fatal: Could not read from remote repository.

Please make sure you have the correct access rights

Thats how I`ve fixed it!! Go to the project directory using the Terminal and check it out

$git remote -v

You will get something like this:

origin  ssh://[email protected]/yourGithubUserName/yourRepo.git (fetch)
origin  ssh://[email protected]/yourGithubUserName/yourRepo.git (push)

If you are using anything different then [email protected], open the config file on git directory by typing the command:

vi .git/config

And configure the line

[remote "origin"]

url = ssh://[email protected]/yourGithubUserName/yourRepo.git

fetch = +refs/heads/*:refs/remotes/origin/

Iterate through pairs of items in a Python list

>>> a = [5, 7, 11, 4, 5]
>>> for n,k in enumerate(a[:-1]):
...     print a[n],a[n+1]
...
5 7
7 11
11 4
4 5

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

How to convert Excel values into buckets?

The right tool for that is to create a range with your limits and the corresponding names. You can then use the vlookup() function, with the 4th parameter set to Trueto create a range lookup.

enter image description here

Note: my PC uses ; as separator, yours might use ,.
Adjust formula according to your regional settings.

Does IMDB provide an API?

new api @ http://www.omdbapi.com

edit: due to legal issues had to move the service to a new domain :)

Numpy array dimensions

You can use .shape

In: a = np.array([[1,2,3],[4,5,6]])
In: a.shape
Out: (2, 3)
In: a.shape[0] # x axis
Out: 2
In: a.shape[1] # y axis
Out: 3

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

I haven't figure out the reason but reinstalling the .pfx certificate(both in current user and local machine) works for me.

Does MySQL ignore null values on unique constraints?

Yes, MySQL allows multiple NULLs in a column with a unique constraint.

CREATE TABLE table1 (x INT NULL UNIQUE);
INSERT table1 VALUES (1);
INSERT table1 VALUES (1);   -- Duplicate entry '1' for key 'x'
INSERT table1 VALUES (NULL);
INSERT table1 VALUES (NULL);
SELECT * FROM table1;

Result:

x
NULL
NULL
1

This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

I found the answer, and in spite of what I reported, it was NOT browser specific. The bug was in my function code, and would have occurred in any browser. It boils down to this. I had two lines in my code that were FireFox/FireBug specific. They used console.log. In IE, they threw an error, so I commented them out (or so I thought). I did a crappy job commenting them out, and broke the bracketing in my function.

Original Code (with console.log in it):

if (sxti.length <= 50) console.log('sxti=' + sxti);
if (sxph.length <= 50) console.log('sxph=' + sxph);

Broken Code (misplaced brackets inside comments):

if (sxti.length <= 50) { //console.log('sxti=' + sxti); }
if (sxph.length <= 50) { //console.log('sxph=' + sxph); }

Fixed Code (fixed brackets outside comments):

if (sxti.length <= 50) { }//console.log('sxti=' + sxti);
if (sxph.length <= 50) { }//console.log('sxph=' + sxph);

So, it was my own sloppy coding. The function really wasn't defined, because a syntax error kept it from being closed.

Oh well, live and learn. ;)

AngularJS: How to run additional code after AngularJS has rendered a template?

First, the right place to mess with rendering are directives. My advice would be to wrap DOM manipulating jQuery plugins by directives like this one.

I had the same problem and came up with this snippet. It uses $watch and $evalAsync to ensure your code runs after directives like ng-repeat have been resolved and templates like {{ value }} got rendered.

app.directive('name', function() {
    return {
        link: function($scope, element, attrs) {
            // Trigger when number of children changes,
            // including by directives like ng-repeat
            var watch = $scope.$watch(function() {
                return element.children().length;
            }, function() {
                // Wait for templates to render
                $scope.$evalAsync(function() {
                    // Finally, directives are evaluated
                    // and templates are renderer here
                    var children = element.children();
                    console.log(children);
                });
            });
        },
    };
});

Hope this can help you prevent some struggle.

How can I execute a python script from an html button?

you could use text files to trasfer the data using PHP and reading the text file in python

Ruby get object keys as array

Like taro said, keys returns the array of keys of your Hash:

http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys

You'll find all the different methods available for each class.

If you don't know what you're dealing with:

 puts my_unknown_variable.class.to_s

This will output the class name.

Why do I always get the same sequence of random numbers with rand()?

None of you guys are answering his question.

with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?

From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

Convert HTML + CSS to PDF

Just to bump the thread, I've tried DOMPDF and it worked perfectly. I've used DIV and other block level elements to position everything, I kept it strictly CSS 2.1 and it played very nicely.

Is there a naming convention for git repositories?

I'd go for purchase-rest-service. Reasons:

  1. What is "pur chase rests ervice"? Long, concatenated words are hard to understand. I know, I'm German. "Donaudampfschifffahrtskapitänspatentausfüllungsassistentenausschreibungsstellenbewerbung."

  2. "_" is harder to type than "-"

Rails - controller action name to string

This snippet works for Rails 3

class ReportsController < ApplicationController

  def summary
    logger.debug self.class.to_s + "." + self.action_name
  end

end

will print

. . .
ReportsController.summary
. . .

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Pehaps...ok, very likely, I'm missing something, but why not just create an object type, say NSNumber, as a container to your non-object type variable, such as CGFloat?

CGFloat myFloat = 2.0; 
NSNumber *myNumber = [NSNumber numberWithFloat:myFloat];

[self performSelector:@selector(MyCalculatorMethod:) withObject:myNumber afterDelay:5.0];

How do I get the file extension of a file in Java?

I like the simplicity of spectre's answer, and linked in one of his comments is a link to another answer that fixes dots in file paths, on another question, made by EboMike.

Without implementing some sort of third party API, I suggest:

private String getFileExtension(File file) {

    String name = file.getName().substring(Math.max(file.getName().lastIndexOf('/'),
            file.getName().lastIndexOf('\\')) < 0 ? 0 : Math.max(file.getName().lastIndexOf('/'),
            file.getName().lastIndexOf('\\')));
    int lastIndexOf = name.lastIndexOf(".");
    if (lastIndexOf == -1) {
        return ""; // empty extension
    }
    return name.substring(lastIndexOf + 1); // doesn't return "." with extension
}

Something like this may be useful in, say, any of ImageIO's write methods, where the file format has to be passed in.

Why use a whole third party API when you can DIY?

Random color generator

Who can beat it?

'#' + Math.random().toString(16).substr(-6);

It is guaranteed to work all the time: http://jsbin.com/OjELIfo/2/edit

Based on eterps's comment, the code above can still generate shorter strings if the hexadecimal representation of the random color is very short (0.730224609375 => 0.baf).

This code should work in all cases:

function makeRandomColor(){
  var c = '';
  while (c.length < 7) {
    c += (Math.random()).toString(16).substr(-6).substr(-1)
  }
  return '#' + c;
}

WPF Add a Border to a TextBlock

A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label

See this link for more on the differences between a TextBlock and other Controls

WebSocket with SSL

The WebSocket connection starts its life with an HTTP or HTTPS handshake. When the page is accessed through HTTP, you can use WS or WSS (WebSocket secure: WS over TLS) . However, when your page is loaded through HTTPS, you can only use WSS - browsers don't allow to "downgrade" security.

Finding and removing non ascii characters from an Oracle Varchar2

If you use the ASCIISTR function to convert the Unicode to literals of the form \nnnn, you can then use REGEXP_REPLACE to strip those literals out, like so...

UPDATE table SET field = REGEXP_REPLACE(ASCIISTR(field), '\\[[:xdigit:]]{4}', '')

...where field and table are your field and table names respectively.

Why Doesn't C# Allow Static Methods to Implement an Interface?

Interfaces are abstract sets of defined available functionality.

Whether or not a method in that interface behaves as static or not is an implementation detail that should be hidden behind the interface. It would be wrong to define an interface method as static because you would be unnecessarily forcing the method to be implemented in a certain way.

If methods were defined as static, the class implementing the interface wouldn't be as encapsulated as it could be. Encapsulation is a good thing to strive for in object oriented design (I won't go into why, you can read that here: http://en.wikipedia.org/wiki/Object-oriented). For this reason, static methods aren't permitted in interfaces.

Change onClick attribute with javascript

Using Jquery instead of Javascript, use 'attr' property instead of 'setAttribute'

like

$('buttonLED'+id).attr('onclick','writeLED(1,1)')

estimating of testing effort as a percentage of development time

The Google Testing Blog discussed this problem recently:

So a naive answer is that writing test carries a 10% tax. But, we pay taxes in order to get something in return.

(snip)

These benefits translate to real value today as well as tomorrow. I write tests, because the additional benefits I get more than offset the additional cost of 10%. Even if I don't include the long term benefits, the value I get from test today are well worth it. I am faster in developing code with test. How much, well that depends on the complexity of the code. The more complex the thing you are trying to build is (more ifs/loops/dependencies) the greater the benefit of tests are.

jQuery Set Select Index

Try this:

$('select#mySelect').prop('selectedIndex', optionIndex);

Eventually, trigger a .change event :

$('select#mySelect').prop('selectedIndex', optionIndex).change();

How to set environment variables in Python?

Environment variables must be strings, so use

os.environ["DEBUSSY"] = "1"

to set the variable DEBUSSY to the string 1.

To access this variable later, simply use:

print(os.environ["DEBUSSY"])

Child processes automatically inherit the environment variables of the parent process -- no special action on your part is required.

Array formula on Excel for Mac

Found a solution to Excel Mac2016 as having to paste the code into the relevant cell, enter, then go to the end of the formula within the header bar and enter the following:

Enter a formula as an array formula Image + SHIFT + RETURN or CONTROL + SHIFT + RETURN

Add text to Existing PDF using Python

Leveraging David Dehghan's answer above, the following works in Python 2.7.13:

from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger

import StringIO

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(290, 720, "Hello world")
can.save()

#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader("original.pdf")
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

Changing image on hover with CSS/HTML

The problem is that you set the first image through 'src' attribute and on hover added to the image a background-image. try this:

in html use:

<img id="Library">

then in css:

#Library {
    height: 70px;
    width: 120px;
    background-image: url('LibraryTransparent.png');
}

#Library:hover {
    background-image: url('LibraryHoverTrans.png');
}

Switch with if, else if, else, and loops inside case

In this case, I'd recommend using break labels.

http://www.java-examples.com/break-statement

This way you can specifically call it outside of the for loop.

How to remove a package in sublime text 2

Simple steps for remove any package from Sublime as phpfmt, Xdebug etc..

1- Go to Sublime menu-> Preference or press Ctrl+Shift+P .
2- Choose -> Remove package option, after you choosing it will display all   packge installed in your sublime, select one of them.
3. After selection it will remove, or for better you can restart your system.

Interface/enum listing standard mime-type constants

There's also a MediaType class in androidannotations in case you want to use with android! See here.

jQuery if Element has an ID?

You can do this:

if ($(".parent a[Id]").length > 0) {

    /* then do something here */

}

Remove lines that contain certain string

Use python-textops package :

from textops import *

'oldfile.txt' | cat() | grepv('bad') | tofile('newfile.txt')

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

@interface UIDevice (Screen)
typedef enum
{
    iPhone          = 1 << 1,
    iPhoneRetina    = 1 << 2,
    iPhone5         = 1 << 3,
    iPad            = 1 << 4,
    iPadRetina      = 1 << 5

} DeviceType;

+ (DeviceType)deviceType;
@end

.m

#import "UIDevice+Screen.h"
@implementation UIDevice (Screen)

+ (DeviceType)deviceType
{
    DeviceType thisDevice = 0;
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    {
        thisDevice |= iPhone;
        if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
        {
            thisDevice |= iPhoneRetina;
            if ([[UIScreen mainScreen] bounds].size.height == 568)
                thisDevice |= iPhone5;
        }
    }
    else
    {
        thisDevice |= iPad;
        if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
            thisDevice |= iPadRetina;
    }
    return thisDevice;
}

@end

This way, if you want to detect whether it is just an iPhone or iPad (regardless of screen-size), you just use:

if ([UIDevice deviceType] & iPhone) 

or

if ([UIDevice deviceType] & iPad)

If you want to detect just the iPhone 5, you can use

if ([UIDevice deviceType] & iPhone5)

As opposed to Malcoms answer where you would need to check just to figure out if it's an iPhone,

if ([UIDevice currentResolution] == UIDevice_iPhoneHiRes || 
    [UIDevice currentResolution] == UIDevice_iPhoneStandardRes || 
    [UIDevice currentResolution] == UIDevice_iPhoneTallerHiRes)`

Neither way has a major advantage over one another, it is just a personal preference.

Show/hide image with JavaScript

You can do this with jquery just visit http://jquery.com/ to get the link then do something like this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').show('slow');
      });
   });
</script>

or if you would like the link to turn the image on and off do this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none;" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').toggle();
      });
   });
</script>

Check if a variable is of function type

The solution as some previous answers has shown is to use typeof. the following is a code snippet In NodeJs,

    function startx() {
      console.log("startx function called.");
    }

 var fct= {};
 fct["/startx"] = startx;

if (typeof fct[/startx] === 'function') { //check if function then execute it
    fct[/startx]();
  }

JavaScript DOM remove element

removeChild should be invoked on the parent, i.e.:

parent.removeChild(child);

In your example, you should be doing something like:

if (frameid) {
    frameid.parentNode.removeChild(frameid);
}

Git: How to check if a local repo is up to date?

git remote show origin


Enter passphrase for key ....ssh/id_rsa:
* remote origin
  Fetch URL: [email protected]:mamaque/systems.git
  Push  URL: [email protected]:mamaque/systems.git 

  HEAD branch: main
  Remote branch:
    main tracked
   Local ref configured for 'git push':

main pushes to main (up-to-date) Both are up to date
main pushes to main (fast-forwardable) Remote can be updated with Local
main pushes to main (local out of date) Local can be update with Remote

How to make a <div> always full screen?

Here's the shortest solution, based on vh. Please note that vh is not supported in some older browsers.

CSS:

div {
    width: 100%;
    height: 100vh;
}

HTML:

<div>This div is fullscreen :)</div>

javascript get x and y coordinates on mouse click

simple solution is this:

game.js:

document.addEventListener('click', printMousePos, true);
function printMousePos(e){

      cursorX = e.pageX;
      cursorY= e.pageY;
      $( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
}

git pull remote branch cannot find remote ref

check your branch on your repo. maybe someone delete it.

What are the differences between Visual Studio Code and Visual Studio?

Complementing the previous answers, one big difference between both is that Visual Studio Code comes in a so called "portable" version that does not require full administrative permissions to run on Windows and can be placed in a removable drive for convenience.

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

Similar questions are here

detect line breaks in a text area input

detect line break in textarea

You can try this:

_x000D_
_x000D_
var submit = document.getElementById('submit');_x000D_
_x000D_
submit.addEventListener('click', function(){_x000D_
var textContent = document.querySelector('textarea').value;_x000D_
  _x000D_
document.getElementById('output').innerHTML = textContent.replace(/\n/g, '<br/>');_x000D_
  _x000D_
_x000D_
});
_x000D_
<textarea cols=30 rows=10 >This is some text_x000D_
this is another text_x000D_
_x000D_
Another text again and again</textarea>_x000D_
<input type='submit' id='submit'>_x000D_
_x000D_
_x000D_
<p id='output'></p>
_x000D_
_x000D_
_x000D_

document.querySelector('textarea').value; will get the text content of the textarea and textContent.replace(/\n/g, '<br/>') will find all the newline character in the source code /\n/g in the content and replace it with the html line-break <br/>.


Another option is to use the html <pre> tag. See the demo below

_x000D_
_x000D_
var submit = document.getElementById('submit');_x000D_
_x000D_
submit.addEventListener('click', function(){_x000D_
_x000D_
  var content = '<pre>';_x000D_
  _x000D_
  var textContent = document.querySelector('textarea').value;_x000D_
  _x000D_
  content += textContent;_x000D_
  _x000D_
  content += '</pre>';_x000D_
_x000D_
  document.getElementById('output').innerHTML = content;_x000D_
_x000D_
});
_x000D_
<textarea cols=30 rows=10>This is some text_x000D_
this is another text_x000D_
_x000D_
Another text again and again </textarea>_x000D_
<input type='submit' id='submit'>_x000D_
_x000D_
<div id='output'> </div>
_x000D_
_x000D_
_x000D_

How do I connect to my existing Git repository using Visual Studio Code?

Use the Git GUI in the Git plugin.

Clone your online repository with the URL which you have.

After cloning, make changes to the files. When you make changes, you can see the number changes. Commit those changes.

Fetch from the remote (to check if anything is updated while you are working).

If the fetch operation gives you an update about the changes in the remote repository, make a pull operation which will update your copy in Visual Studio Code. Otherwise, do not make a pull operation if there aren't any changes in the remote repository.

Push your changes to the upstream remote repository by making a push operation.

Move existing, uncommitted work to a new branch in Git

There is actually a really easy way to do this with GitHub Desktop now that I don't believe was a feature before.

All you need to do is switch to the new branch in GitHub Desktop, and it will prompt you to leave your changes on the current branch (which will be stashed), or to bring your changes with you to the new branch. Just choose the second option, to bring the changes to the new branch. You can then commit as usual.

GitHub Desktop

Why use #define instead of a variable

Define is evaluated before compilation by the pre-processor, while variables are referenced at run-time. This means you control how your application is built (not how it runs)

Here are a couple examples that use define which cannot be replaced by a variable:

  1. #define min(i, j) (((i) < (j)) ? (i) : (j))
    note this is evaluated by the pre-processor, not during runtime

  2. http://msdn.microsoft.com/en-us/library/8fskxacy.aspx

Java - Getting Data from MySQL database

Something like this would do:

public static void main(String[] args) {

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    String url = "jdbc:mysql://localhost/t";
    String user = "";
    String password = "";

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(url, user, password);
        st = con.createStatement();
        rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");

        if (rs.next()) {//get first result
            System.out.println(rs.getString(1));//coloumn 1
        }

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Version.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.WARNING, ex.getMessage(), ex);
        }
    }
}

you can iterate over the results with a while like this:

while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}

There are many other great tutorial out there like these to list a few:

As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself

References:

Adding a favicon to a static HTML page

I know its older post but still posting for someone like me. This worked for me

<link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />

put your favicon icon on root directory..

Max retries exceeded with URL in requests

Just do this,

Paste the following code in place of page = requests.get(url):

import time

page = ''
while page == '':
    try:
        page = requests.get(url)
        break
    except:
        print("Connection refused by the server..")
        print("Let me sleep for 5 seconds")
        print("ZZzzzz...")
        time.sleep(5)
        print("Was a nice sleep, now let me continue...")
        continue

You're welcome :)

How to add two edit text fields in an alert dialog

I found another set of examples for customizing an AlertDialog from a guy named Mossila. I think they're better than Google's examples. To quickly see Google's API demos, you must import their demo jar(s) into your project, which you probably don't want.

But Mossila's example code is fully self-contained. It can be directly cut-and-pasted into your project. It just works! Then you only need to tweak it to your needs. See here

Creating an XmlNode/XmlElement in C# without an XmlDocument?

You may want to look at how you can use the built-in features of .NET to serialize and deserialize an object into XML, rather than creating a ToXML() method on every class that is essentially just a Data Transfer Object.

I have used these techniques successfully on a couple of projects but don’t have the implementation details handy right now. I will try to update my answer with my own examples sometime later.

Here's a couple of examples that Google returned:

XML Serialization in .NET by Venkat Subramaniam http://www.agiledeveloper.com/articles/XMLSerialization.pdf

How to Serialize and Deserialize an object into XML http://www.dotnetfunda.com/articles/article98.aspx

Customize your .NET object XML serialization with .NET XML attributes http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx

Inline style to act as :hover in CSS

A simple solution:

   <a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>

Or

<script>
 /** Change the style **/
 function overStyle(object){
    object.style.color = 'orange';
    // Change some other properties ...
 }

 /** Restores the style **/
 function outStyle(object){
    object.style.color = 'orange';
    // Restore the rest ...
 }
</script>

<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>

Please initialize the log4j system properly warning

just configure your log4j property file path in beginning of main method: e.g.: PropertyConfigurator.configure("D:\files\log4j.properties");

HTML - how can I show tooltip ONLY when ellipsis is activated

If you want to do this solely using javascript, I would do the following. Give the span an id attribute (so that it can easily be retrieved from the DOM) and place all the content in an attribute named 'content':

<span id='myDataId' style='text-overflow: ellipsis; overflow : hidden;
 white-space: nowrap; width: 71;' content='{$myData}'>${myData}</span>

Then, in your javascript, you can do the following after the element has been inserted into the DOM.

var elemInnerText, elemContent;
elemInnerText = document.getElementById("myDataId").innerText;
elemContent = document.getElementById("myDataId").getAttribute('content')
if(elemInnerText.length <= elemContent.length)
{
   document.getElementById("myDataId").setAttribute('title', elemContent); 
}

Of course, if you're using javascript to insert the span into the DOM, you could just keep the content in a variable before inserting it. This way you don't need a content attribute on the span.

There are more elegant solutions than this if you want to use jQuery.

Pass command parameter to method in ViewModel in WPF?

Just using Data Binding syntax. For example,

<Button x:Name="btn" 
         Content="Click" 
         Command="{Binding ClickCmd}" 
         CommandParameter="{Binding ElementName=btn,Path=Content}" /> 

Not only can we use Data Binding to get some data from View Models, but also pass data back to View Models. In CommandParameter, must use ElementName to declare binding source explicitly.

How do I add an existing Solution to GitHub from Visual Studio 2013

OK this worked for me.

  1. Open the solution in Visual Studio 2013
  2. Select File | Add to Source Control
  3. Select the Microsoft Git Provider

That creates a local GIT repository

  1. Surf to GitHub
  2. Create a new repository DO NOT SELECT Initialize this repository with a README

That creates an empty repository with no Master branch

  1. Once created open the repository and copy the URL (it's on the right of the screen in the current version)
  2. Go back to Visual Studio
    • Make sure you have the Microsoft Git Provider selected under Tools/Options/Source Control/Plug-in Selection
  3. Open Team Explorer
  4. Select Home | Unsynced Commits
  5. Enter the GitHub URL into the yellow box (use HTTPS URL, not the default shown SSH one)
  6. Click Publish
  7. Select Home | Changes
  8. Add a Commit comment
  9. Select Commit and Push from the drop down

Your solution is now in GitHub

Direct download from Google Drive using Google Drive API

Using a Service Account might work for you.

how to calculate binary search complexity

ok see this
for(i=0;i<n;n=n/2)
{
i++;
}
1. Suppose at i=k the loop terminate. i.e. the loop execute k times.

2. at each iteration n is divided by half.

2.a n=n/2                   .... AT I=1
2.b n=(n/2)/2=n/(2^2)
2.c n=((n/2)/2)/2=n/(2^3)....... aT I=3
2.d n=(((n/2)/2)/2)/2=n/(2^4)

So at i=k , n=1 which is obtain by dividing n  2^k times
n=2^k
1=n/2^k 
k=log(N)  //base 2

jQuery set radio button

You can simply use:

$("input[name='cols']").click();

What does the variable $this mean in PHP?

Generally, this keyword is used inside a class, generally with in the member functions to access non-static members of a class(variables or functions) for the current object.

  1. this keyword should be preceded with a $ symbol.
  2. In case of this operator, we use the -> symbol.
  3. Whereas, $this will refer the member variables and function for a particular instance.

Let's take an example to understand the usage of $this.

<?php
class Hero {
    // first name of hero
    private $name;
    
    // public function to set value for name (setter method)
    public function setName($name) {
        $this->name = $name;
    }
    
    // public function to get value of name (getter method)
    public function getName() {
        return $this->name;
    }
}

// creating class object
$stark = new Hero();

// calling the public function to set fname
$stark->setName("IRON MAN");

// getting the value of the name variable
echo "I Am " . $stark->getName();
?>

OUTPUT: I am IRON MAN

NOTE: A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created.

CSS animation delay in repeating

Heres a little snippet that shows the same thing for 75% of the time, then it slides. This repeat schema emulates delay nicely:

@-webkit-keyframes slide    {
0%   {background-position: 0 0;}
25%  {background-position: 0 0;}
50%  {background-position: 0 0;}
75%  {background-position: 0 0;}
100% {background-position: 13em 0;}
}

@-moz-keyframes slide       {
0%   {background-position: 0 0;}
25%  {background-position: 0 0;}
50%  {background-position: 0 0;}
75%  {background-position: 0 0;}
100% {background-position: 13em 0;}
}

@keyframes slide            {
0%   {background-position: 0 0;}
25%  {background-position: 0 0;}
50%  {background-position: 0 0;}
75%  {background-position: 0 0;}
100% {background-position: 13em 0;}
}

How can I count the number of children?

What if you are using this to determine the current selector to find its children so this holds: <ol> then there is <li>s under how to write a selector var count = $(this+"> li").length; wont work..

Method to get all files within folder and subfolders that will return a list

I am not sure of why you're adding the strings to files, which is declared as a field rather than a temporary variable. You could change the signature of DirSearch to:

private List<string> DirSearch(string sDir)

And, after the catch block, add:

return files;

Alternatively, you could create a temporary variable inside of your method and return it, which seems to me the approach you might desire. Otherwise, each time you call that method, the newly found strings will be added to the same list as before and you'll have duplicates.

How to print a list with integers without the brackets, commas and no quotes?

Something like this should do it:

for element in list_:
   sys.stdout.write(str(element))

How to loop through all the properties of a class?

Note that if the object you are talking about has a custom property model (such as DataRowView etc for DataTable), then you need to use TypeDescriptor; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):

foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
    Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}

This also provides easy access to things like TypeConverter for formatting:

    string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));

SQL Server find and replace specific word in all rows of specific column

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'

or simply this if you are sure that you have no values like this CKIT002

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')

How do you truncate all tables in a database using TSQL?

An alternative option I like to use with MSSQL Server Deveploper or Enterprise is to create a snapshot of the database immediately after creating the empty schema. At that point you can just keep restoring the database back to the snapshot.

How to join (merge) data frames (inner, outer, left, right)

New in 2014:

Especially if you're also interested in data manipulation in general (including sorting, filtering, subsetting, summarizing etc.), you should definitely take a look at dplyr, which comes with a variety of functions all designed to facilitate your work specifically with data frames and certain other database types. It even offers quite an elaborate SQL interface, and even a function to convert (most) SQL code directly into R.

The four joining-related functions in the dplyr package are (to quote):

  • inner_join(x, y, by = NULL, copy = FALSE, ...): return all rows from x where there are matching values in y, and all columns from x and y
  • left_join(x, y, by = NULL, copy = FALSE, ...): return all rows from x, and all columns from x and y
  • semi_join(x, y, by = NULL, copy = FALSE, ...): return all rows from x where there are matching values in y, keeping just columns from x.
  • anti_join(x, y, by = NULL, copy = FALSE, ...): return all rows from x where there are not matching values in y, keeping just columns from x

It's all here in great detail.

Selecting columns can be done by select(df,"column"). If that's not SQL-ish enough for you, then there's the sql() function, into which you can enter SQL code as-is, and it will do the operation you specified just like you were writing in R all along (for more information, please refer to the dplyr/databases vignette). For example, if applied correctly, sql("SELECT * FROM hflights") will select all the columns from the "hflights" dplyr table (a "tbl").

SELECT list is not in GROUP BY clause and contains nonaggregated column

country.code is not in your group by statement, and is not an aggregate (wrapped in an aggregate function).

https://www.w3schools.com/sql/sql_ref_sqlserver.asp

When would you use the different git merge strategies?

With Git 2.30 (Q1 2021), there will be a new merge strategy: ORT ("Ostensibly Recursive's Twin").

git merge -s ort

This comes from this thread from Elijah Newren:

For now, I'm calling it "Ostensibly Recursive's Twin", or "ort" for short. > At first, people shouldn't be able to notice any difference between it and the current recursive strategy, other than the fact that I think I can make it a bit faster (especially for big repos).

But it should allow me to fix some (admittedly corner case) bugs that are harder to handle in the current design, and I think that a merge that doesn't touch $GIT_WORK_TREE or $GIT_INDEX_FILE will allow for some fun new features.
That's the hope anyway.

Problem:

In the ideal world, we should:

  • ask unpack_trees() to do "read-tree -m" without "-u";

  • do all the merge-recursive computations in-core and prepare the resulting index, while keeping the current index intact;

  • compare the current in-core index and the resulting in-core index, and notice the paths that need to be added, updated or removed in the working tree, and ensure that there is no loss of information when the change is reflected to the working tree;
    E.g. the result wants to create a file where the working tree currently has a directory with non-expendable contents in it, the result wants to remove a file where the working tree file has local modification, etc.;
    And then finally

  • carry out the working tree update to make it match what the resulting in-core index says it should look like.

Result:

See commit 14c4586 (02 Nov 2020), commit fe1a21d (29 Oct 2020), and commit 47b1e89, commit 17e5574 (27 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit a1f9595, 18 Nov 2020)

merge-ort: barebones API of new merge strategy with empty implementation

Signed-off-by: Elijah Newren

This is the beginning of a new merge strategy.

While there are some API differences, and the implementation has some differences in behavior, it is essentially meant as an eventual drop-in replacement for merge-recursive.c.

However, it is being built to exist side-by-side with merge-recursive so that we have plenty of time to find out how those differences pan out in the real world while people can still fall back to merge-recursive.
(Also, I intend to avoid modifying merge-recursive during this process, to keep it stable.)

The primary difference noticable here is that the updating of the working tree and index is not done simultaneously with the merge algorithm, but is a separate post-processing step.
The new API is designed so that one can do repeated merges (e.g. during a rebase or cherry-pick) and only update the index and working tree one time at the end instead of updating it with every intermediate result.

Also, one can perform a merge between two branches, neither of which match the index or the working tree, without clobbering the index or working tree.

And:

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

t6423, t6436: note improved ort handling with dirty files

Signed-off-by: Elijah Newren

The "recursive" backend relies on unpack_trees() to check if unstaged changes would be overwritten by a merge, but unpack_trees() does not understand renames -- and once it returns, it has already written many updates to the working tree and index.
As such, "recursive" had to do a special 4-way merge where it would need to also treat the working copy as an extra source of differences that we had to carefully avoid overwriting and resulting in moving files to new locations to avoid conflicts.

The "ort" backend, by contrast, does the complete merge inmemory, and only updates the index and working copy as a post-processing step.
If there are dirty files in the way, it can simply abort the merge.

t6423: expect improved conflict markers labels in the ort backend

Signed-off-by: Elijah Newren

Conflict markers carry an extra annotation of the form REF-OR-COMMIT:FILENAME to help distinguish where the content is coming from, with the :FILENAME piece being left off if it is the same for both sides of history (thus only renames with content conflicts carry that part of the annotation).

However, there were cases where the :FILENAME annotation was accidentally left off, due to merge-recursive's every-codepath-needs-a-copy-of-all-special-case-code format.

t6404, t6423: expect improved rename/delete handling in ort backend

Signed-off-by: Elijah Newren

When a file is renamed and has content conflicts, merge-recursive does not have some stages for the old filename and some stages for the new filename in the index; instead it copies all the stages corresponding to the old filename over to the corresponding locations for the new filename, so that there are three higher order stages all corresponding to the new filename.

Doing things this way makes it easier for the user to access the different versions and to resolve the conflict (no need to manually 'git rm '(man) the old version as well as 'git add'(man) the new one).

rename/deletes should be handled similarly -- there should be two stages for the renamed file rather than just one.
We do not want to destabilize merge-recursive right now, so instead update relevant tests to have different expectations depending on whether the "recursive" or "ort" merge strategies are in use.


With Git 2.30 (Q1 2021), Preparation for a new merge strategy.

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

merge tests: expect improved directory/file conflict handling in ort

Signed-off-by: Elijah Newren

merge-recursive.c is built on the idea of running unpack_trees() and then "doing minor touch-ups" to get the result.
Unfortunately, unpack_trees() was run in an update-as-it-goes mode, leading merge-recursive.c to follow suit and end up with an immediate evaluation and fix-it-up-as-you-go design.

Some things like directory/file conflicts are not well representable in the index data structure, and required special extra code to handle.
But then when it was discovered that rename/delete conflicts could also be involved in directory/file conflicts, the special directory/file conflict handling code had to be copied to the rename/delete codepath.
...and then it had to be copied for modify/delete, and for rename/rename(1to2) conflicts, ...and yet it still missed some.
Further, when it was discovered that there were also file/submodule conflicts and submodule/directory conflicts, we needed to copy the special submodule handling code to all the special cases throughout the codebase.

And then it was discovered that our handling of directory/file conflicts was suboptimal because it would create untracked files to store the contents of the conflicting file, which would not be cleaned up if someone were to run a 'git merge --abort'(man) or 'git rebase --abort'(man).

It was also difficult or scary to try to add or remove the index entries corresponding to these files given the directory/file conflict in the index.
But changing merge-recursive.c to handle these correctly was a royal pain because there were so many sites in the code with similar but not identical code for handling directory/file/submodule conflicts that would all need to be updated.

I have worked hard to push all directory/file/submodule conflict handling in merge-ort through a single codepath, and avoid creating untracked files for storing tracked content (it does record things at alternate paths, but makes sure they have higher-order stages in the index).


With Git 2.31 (Q1 2021), the merge backend "done right" starts to emerge.
Example:

See commit 6d37ca2 (11 Nov 2020) by Junio C Hamano (gitster).
See commit 89422d2, commit ef2b369, commit 70912f6, commit 6681ce5, commit 9fefce6, commit bb470f4, commit ee4012d, commit a9945bb, commit 8adffaa, commit 6a02dd9, commit 291f29c, commit 98bf984, commit 34e557a, commit 885f006, commit d2bc199, commit 0c0d705, commit c801717, commit e4171b1, commit 231e2dd, commit 5b59c3d (13 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit f9d29da, 06 Jan 2021)

merge-ort: add implementation of record_conflicted_index_entries()

Signed-off-by: Elijah Newren

After checkout(), the working tree has the appropriate contents, and the index matches the working copy.
That means that all unmodified and cleanly merged files have correct index entries, but conflicted entries need to be updated.

We do this by looping over the conflicted entries, marking the existing index entry for the path with CE_REMOVE, adding new higher order staged for the path at the end of the index (ignoring normal index sort order), and then at the end of the loop removing the CE_REMOVED-marked cache entries and sorting the index.


With Git 2.31 (Q1 2021), rename detection is added to the "ORT" merge strategy.

See commit 6fcccbd, commit f1665e6, commit 35e47e3, commit 2e91ddd, commit 53e88a0, commit af1e56c (15 Dec 2020), and commit c2d267d, commit 965a7bc, commit f39d05c, commit e1a124e, commit 864075e (14 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 2856089, 25 Jan 2021)

Example:

merge-ort: add implementation of normal rename handling

Signed-off-by: Elijah Newren

Implement handling of normal renames.
This code replaces the following from merge-recurisve.c:

  • the code relevant to RENAME_NORMAL in process_renames()
  • the RENAME_NORMAL case of process_entry()

Also, there is some shared code from merge-recursive.c for multiple different rename cases which we will no longer need for this case (or other rename cases):

  • handle_rename_normal()
  • setup_rename_conflict_info()

The consolidation of four separate codepaths into one is made possible by a change in design: process_renames() tweaks the conflict_info entries within opt->priv->paths such that process_entry() can then handle all the non-rename conflict types (directory/file, modify/delete, etc.) orthogonally.

This means we're much less likely to miss special implementation of some kind of combination of conflict types (see commits brought in by 66c62ea ("Merge branch 'en/merge-tests'", 2020-11-18, Git v2.30.0-rc0 -- merge listed in batch #6), especially commit ef52778 ("merge tests: expect improved directory/file conflict handling in ort", 2020-10-26, Git v2.30.0-rc0 -- merge listed in batch #6) for more details).

That, together with letting worktree/index updating be handled orthogonally in the merge_switch_to_result() function, dramatically simplifies the code for various special rename cases.

(To be fair, the code for handling normal renames wasn't all that complicated beforehand, but it's still much simpler now.)

And, still with Git 2.31 (Q1 2021), With Git 2.31 (Q1 2021), oRT merge strategy learns more support for merge conflicts.

See commit 4ef88fc, commit 4204cd5, commit 70f19c7, commit c73cda7, commit f591c47, commit 62fdec1, commit 991bbdc, commit 5a1a1e8, commit 23366d2, commit 0ccfa4e (01 Jan 2021) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit b65b9ff, 05 Feb 2021)

merge-ort: add handling for different types of files at same path

Signed-off-by: Elijah Newren

Add some handling that explicitly considers collisions of the following types:

  • file/submodule
  • file/symlink
  • submodule/symlink> Leaving them as conflicts at the same path are hard for users to resolve, so move one or both of them aside so that they each get their own path.

Note that in the case of recursive handling (i.e.
call_depth > 0), we can just use the merge base of the two merge bases as the merge result much like we do with modify/delete conflicts, binary files, conflicting submodule values, and so on.

custom facebook share button

You can use facebook javascript sdk. First add FB Js SDK to your code (please refer to https://developers.facebook.com/docs/javascript)

window.fbAsyncInit = function(){
FB.init({
    appId: 'xxxxx', status: true, cookie: true, xfbml: true }); 
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if(d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; 
    js.async = true;js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
    ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}

So when you want to share something

<a href="someurl.com/some-article" data-image="article-1.jpg" data-title="Article Title" data-desc="Some description for this article" class="btnShare">Share</a>

And finally JS to handle click:

$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));

return false;
});

cleanest way to skip a foreach if array is empty

If variable you need could be boolean false - eg. when no records are returned from database or array - when records are returned, you can do following:

foreach (($result ? $result : array()) as $item)
    echo $item;

Approach with cast((Array)$result) produces an array of count 1 when variable is boolean false which isn't what you probably want.

Which command do I use to generate the build of a Vue app?

For NPM => npm run Build For Yarn => yarn run build

You also can check scripts in package.json file

Powershell import-module doesn't find modules

1.This will search XMLHelpers/XMLHelpers.psm1 in current folder

Import-Module (Resolve-Path('XMLHelpers'))

2.This will search XMLHelpers.psm1 in current folder

Import-Module (Resolve-Path('XMLHelpers.psm1'))

CKEditor instance already exists

For ajax requests,

 for(k in CKEDITOR.instances){
    var instance = CKEDITOR.instances[k];
    instance.destroy()
 }
  CKEDITOR.replaceAll();

this snipped removes all instances from document. Then creates new instances.

Insert auto increment primary key to existing table

An ALTER TABLE statement adding the PRIMARY KEY column works correctly in my testing:

ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;

On a temporary table created for testing purposes, the above statement created the AUTO_INCREMENT id column and inserted auto-increment values for each existing row in the table, starting with 1.

XSD - how to allow elements in any order any number of times?

You should find that the following schema allows the what you have proposed.

  <xs:element name="foo">
    <xs:complexType>
      <xs:sequence minOccurs="0" maxOccurs="unbounded">
        <xs:choice>
          <xs:element maxOccurs="unbounded" name="child1" type="xs:unsignedByte" />
          <xs:element maxOccurs="unbounded" name="child2" type="xs:string" />
        </xs:choice>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

This will allow you to create a file such as:

<?xml version="1.0" encoding="utf-8" ?>
<foo>
  <child1>2</child1>
  <child1>3</child1>
  <child2>test</child2>
  <child2>another-test</child2>
</foo>

Which seems to match your question.

Split text with '\r\n'

This worked for me.

string stringSeparators = "\r\n";
string text = sr.ReadToEnd();
string lines = text.Replace(stringSeparators, "");
lines = lines.Replace("\\r\\n", "\r\n");
Console.WriteLine(lines);

The first replace replaces the \r\n from the text file's new lines, and the second replaces the actual \r\n text that is converted to \\r\\n when the files is read. (When the file is read \ becomes \\).

How to create a readonly textbox in ASP.NET MVC3 Razor

 @Html.TextBox("Receivers", Model, new { @class = "form-control", style = "width: 300px", @readonly = "readonly" })

How to replace unicode characters in string with something else python?

  1. Decode the string to Unicode. Assuming it's UTF-8-encoded:

    str.decode("utf-8")
    
  2. Call the replace method and be sure to pass it a Unicode string as its first argument:

    str.decode("utf-8").replace(u"\u2022", "*")
    
  3. Encode back to UTF-8, if needed:

    str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
    

(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str shadows the built-in type str.)

To add server using sp_addlinkedserver

-- check if server exists in table sys.server

select * from sys.servers

-- set database security

    EXEC sp_configure 'show advanced options', 1
    RECONFIGURE
    GO

    EXEC sp_configure 'ad hoc distributed queries', 1
    RECONFIGURE
    GO

-- add the external dbserver

EXEC sp_addlinkedserver @server='#servername#'

-- add login on external server

EXEC sp_addlinkedsrvlogin '#Servername#', 'false', NULL, '#username#', '#password@123"'

-- control query on remote table

select top (1000) * from [#server#].[#database#].[#schema#].[#table#]

How to increment an iterator by 2?

The very simple answer:

++++iter

The long answer:

You really should get used to writing ++iter instead of iter++. The latter must return (a copy of) the old value, which is different from the new value; this takes time and space.

Note that prefix increment (++iter) takes an lvalue and returns an lvalue, whereas postfix increment (iter++) takes an lvalue and returns an rvalue.

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

How to display a "busy" indicator with jQuery?

You can just show / hide a gif, but you can also embed that to ajaxSetup, so it's called on every ajax request.

$.ajaxSetup({
    beforeSend:function(){
        // show gif here, eg:
        $("#loading").show();
    },
    complete:function(){
        // hide gif here, eg:
        $("#loading").hide();
    }
});

One note is that if you want to do an specific ajax request without having the loading spinner, you can do it like this:

$.ajax({
   global: false,
   // stuff
});

That way the previous $.ajaxSetup we did will not affect the request with global: false.

More details available at: http://api.jquery.com/jQuery.ajaxSetup

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

In case the remote repository is not empty (this is the case if you are using IBM DevOps on hub.jazz.net) then you need to use the following sequence:

cd <localDir>
git init
git add -A .
git pull <url> master
git commit -m "message"
git remote add origin <url>
git push

EDIT 30th Jan 17: Please see comments below, make sure you are on the correct repo!

Error - Unable to access the IIS metabase

You can solve this problem by actually unchecking the IIS tools in your Windows feature list. Then, repair your Visual Studio 2013 installation and make sure Web Developer is checked. It will install IIS 8 with which VS will work nicely.

RunAs A different user when debugging in Visual Studio

This works (I feel so idiotic):

C:\Windows\System32\cmd.exe /C runas /savecred /user:OtherUser DebugTarget.Exe

The above command will ask for your password everytime, so for less frustration, you can use /savecred. You get asked only once. (but works only for Home Edition and Starter, I think)

How to exclude particular class name in CSS selector?

Method 1

The problem with your code is that you are selecting the .remode_hover that is a descendant of .remode_selected. So the first part of getting your code to work correctly is by removing that space

.reMode_selected.reMode_hover:hover

Then, in order to get the style to not work, you have to override the style set by the :hover. In other words, you need to counter the background-color property. So the final code will be

.reMode_selected.reMode_hover:hover {
  background-color:inherit;
}
.reMode_hover:hover {
  background-color: #f0ac00;
}

Fiddle

Method 2

An alternative method would be to use :not(), as stated by others. This will return any element that doesn't have the class or property stated inside the parenthesis. In this case, you would put .remode_selected in there. This will target all elements that don't have a class of .remode_selected

Fiddle

However, I would not recommend this method, because of the fact that it was introduced in CSS3, so browser support is not ideal.

Method 3

A third method would be to use jQuery. You can target the .not() selector, which would be similar to using :not() in CSS, but with much better browser support

Fiddle

How do I diff the same file between two different commits on the same branch?

You can also compare two different files in two different revisions, like this:

git diff <revision_1>:<file_1> <revision_2>:<file_2>

How to silence output in a Bash script?

If you are still struggling to find an answer, specially if you produced a file for the output, and you prefer a clear alternative: echo "hi" | grep "use this hack to hide the oputut :) "

How to clamp an integer to some range?

Avoid writing functions for such small tasks, unless you apply them often, as it will clutter up your code.

for individual values:

min(clamp_max, max(clamp_min, value))

for lists of values:

map(lambda x: min(clamp_max, max(clamp_min, x)), values)

FIFO class in Java

Queues are First In First Out structures. You request is pretty vague, but I am guessing that you need only the basic functionality which usually comes out with Queue structures. You can take a look at how you can implement it here.

With regards to your missing package, it is most likely because you will need to either download or create the package yourself by following that tutorial.

Reload activity in Android

After login I had the same problem so I used

@Override
protected void onRestart() {
    this.recreate();
    super.onRestart();
}

CSS/HTML: Create a glowing border around an Input Field

Below is the code that Bootstrap uses. Colors are bit different but the concept is same. This is if you are using LESS to compile CSS:

// Form control focus state
//
// Generate a customized focus state and for any input with the specified color,
// which defaults to the `@input-focus-border` variable.
//
// We highly encourage you to not customize the default value, but instead use
// this to tweak colors on an as-needed basis. This aesthetic change is based on
// WebKit's default styles, but applicable to a wider range of browsers. Its
// usability and accessibility should be taken into account with any change.
//
// Example usage: change the default blue border and shadow to white for better
// contrast against a dark gray background.

.form-control-focus(@color: @input-border-focus) {
  @color-rgba: rgba(red(@color), green(@color), blue(@color), .6);
  &:focus {
    border-color: @color;
    outline: 0;
    .box-shadow(~"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px @{color-rgba}");
  }
}

If you are not using LESS then here's the compiled version:

.form-control:focus {
    border-color: #66afe9;
    outline: 0;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
}

How to enable C++11/C++0x support in Eclipse CDT?

For me on Eclipse Neon I followed Trismegistos answer here above , YET I also added an additional step:

  • Go to project --> Properties --> C++ General --> Preprocessor Include paths,Macros etc. --> Providers --> CDT Cross GCC Built-in Compiler Settings, append the flag "-std=c++11"

Hit apply and OK.

Cheers,

Guy.

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.

Cancel a vanilla ECMAScript 6 Promise chain

Here's our implementation https://github.com/permettez-moi-de-construire/cancellable-promise

Used like

const {
  cancellablePromise,
  CancelToken,
  CancelError
} = require('@permettezmoideconstruire/cancellable-promise')

const cancelToken = new CancelToken()

const initialPromise = SOMETHING_ASYNC()
const wrappedPromise = cancellablePromise(initialPromise, cancelToken)


// Somewhere, cancel the promise...
cancelToken.cancel()


//Then catch it
wrappedPromise
.then((res) => {
  //Actual, usual fulfill
})
.catch((err) => {
  if(err instanceOf CancelError) {
    //Handle cancel error
  }

  //Handle actual, usual error
})

which :

  • Doesn't touch Promise API
  • Let us make further cancellation inside catch call
  • Rely on cancellation being rejected instead of resolved unlike any other proposal or implementation

Pulls and comments welcome

How does the modulus operator work?

This JSFiddle project could help you to understand how modulus work: http://jsfiddle.net/elazar170/7hhnagrj

The modulus function works something like this:

     function modulus(x,y){
       var m = Math.floor(x / y);
       var r = m * y;
       return x - r;
     }

Adding a custom header to HTTP request using angular.js

I took what you had, and added another X-Testing header

var config = {headers:  {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json;odata=verbose',
        "X-Testing" : "testing"
    }
};

$http.get("/test", config);

And in the Chrome network tab, I see them being sent.

GET /test HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Accept: application/json;odata=verbose
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Authorization: Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==
X-Testing: testing
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Are you not seeing them from the browser, or on the server? Try the browser tooling or a debug proxy and see what is being sent out.

json_encode sparse PHP array as JSON array, not JSON object

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>

Create a Maven project in Eclipse complains "Could not resolve archetype"

click windows-> preferences->Maven. uncheck "Offline" check box. This was not able to download archetype which I was using. When I uncheck it, Everything worked smooth.

Toolbar overlapping below status bar

I removed all lines mentioned below from /res/values-v21/styles.xml and now it is working fine.

 <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 <item name="android:statusBarColor">@android:color/transparent</item>


 <item name="windowActionBar">false</item>
 <item name="android:windowDisablePreview">true</item>

 <item name="windowNoTitle">true</item>

 <item name="android:fitsSystemWindows">true</item>

How do I prevent site scraping?

Sorry, it's really quite hard to do this...

I would suggest that you politely ask them to not use your content (if your content is copyrighted).

If it is and they don't take it down, then you can take furthur action and send them a cease and desist letter.

Generally, whatever you do to prevent scraping will probably end up with a more negative effect, e.g. accessibility, bots/spiders, etc.

TypeError: 'float' object is not subscriptable

PriceList[0] is a float. PriceList[0][1] is trying to access the first element of a float. Instead, do

PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange

or

PriceList[0:7] = [PizzaChange]*7

Function to clear the console in R and RStudio

cat("\f") may be easier to remember than cat("\014").

It works fine for me on Windows 10.

Convert byte[] to char[]

System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();

Substitute the right encoding above: e.g.

System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();

How to use Greek symbols in ggplot2?

You do not need the latex2exp package to do what you wanted to do. The following code would do the trick.

ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) + 
  geom_point() + 
  labs(title=expression("Fuel Efficiency"~(alpha*Omega)), 
color=expression(alpha*Omega), x=expression(Delta~price))

enter image description here

Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*") works, so I suggest giving it a try.

More comments asked about getting ? Price and I find the most straightforward way to achieve that is expression(Delta~price)). If you need to add something before the Greek letter, you can also do this: expression(Indicative~Delta~price) which gets you:

enter image description here

How can I escape a double quote inside double quotes?

Make use of $"string".

In this example, it would be,

dbload=$"load data local infile \"'gfpoint.csv'\" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY \"'\n'\" IGNORE 1 LINES"

Note(from the man page):

A double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted.

how to open *.sdf files?

Try LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0). Best of all it's free!

LINQPad

Steps with version 4.35.1:

  1. click 'Add Connection'

  2. Click Next with 'Build data context automatically' and 'Default(LINQ to SQL)' selected.

  3. Under 'Provider' choose 'SQL CE 4.0'.

  4. Under 'Database' with 'Attach database file' selected, choose 'Browse' to select your .sdf file.

  5. Click 'OK'.

  6. Voila! It should show the tables in .sdf and be able to query it via right clicking the table or writing LINQ code in your favorite .NET language or even SQL. How cool is that?

Duplicate Symbols for Architecture arm64

The problem for me was I had manually included a framework but then also included that same framework in CocoaPods not knowing I did so. Once I removed one or the other, the problem went away

IOException: read failed, socket might closed - Bluetooth on Android 4.3

I have also receive the same IOException, but I find the Android system demo: "BluetoothChat" project is worked. I determined the problem is the UUID.

So i replace my UUID.fromString("00001001-0000-1000-8000-00805F9B34FB") to UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66") and it worked most scene,only sometimes need to restart the Bluetooth device;

Convert AM/PM time to 24 hours format?

Go through following code to convert the DateTime from 12 hrs to 24 hours.

string currentDateString = DateTime.Now.ToString("dd-MMM-yyyy h:mm tt");
DateTime currentDate = Convert.ToDateTime(currentDateString);
Console.WriteLine("String Current Date: " + currentDateString);
Console.WriteLine("Converted Date: " + currentDate.ToString("dd-MMM-yyyy HH:mm"));

Whenever you want the time should be displayed in24 hours use format "HH"

You can refer following link for further details: Custom Date and Time Format Strings

How to import an Excel file into SQL Server?

There are many articles about writing code to import an excel file, but this is a manual/shortcut version:

If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.

The quickest way to get your Excel file into SQL is by using the import wizard:

  1. Open SSMS (Sql Server Management Studio) and connect to the database where you want to import your file into.
  2. Import Data: in SSMS in Object Explorer under 'Databases' right-click the destination database, select Tasks, Import Data. An import wizard will pop up (you can usually just click 'Next' on the first screen).

enter image description here

  1. The next window is 'Choose a Data Source', select Excel:

    • In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).

    • Click the 'Browse' button to select the path to the Excel file you want to import.

    • Select the version of the excel file (97-2003 is usually fine for files with a .XLS extension, or use 2007 for newer files with a .XLSX extension)
    • Tick the 'First Row has headers' checkbox if your excel file contains headers.
    • Click next.

enter image description here

  1. On the 'Choose a Destination' screen, select destination database:
    • Select the 'Server name', Authentication (typically your sql username & password) and select a Database as destination. Click Next.

enter image description here

  1. On the 'Specify Table Copy or Query' window:

    • For simplicity just select 'Copy data from one or more tables or views', click Next.
  2. 'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.

enter image description here

  1. Click Finish.

How to rearrange Pandas column sequence?

You could also do something like this:

df = df[['x', 'y', 'a', 'b']]

You can get the list of columns with:

cols = list(df.columns.values)

The output will produce something like this:

['a', 'b', 'x', 'y']

...which is then easy to rearrange manually before dropping it into the first function

Cannot access a disposed object - How to fix?

You sure the timer isn't outliving the 'dbiSchedule' somehow and firing after the 'dbiSchedule' has been been disposed of?

If that is the case you might be able to recreate it more consistently if the timer fires more quickly thus increasing the chances of you closing the Form just as the timer is firing.

How to list npm user-installed packages?

As of 13 December 2015

npm list illustration

Whilst I found the accepted answer 100% correct, and useful, wished to expand upon it a little based on my own experiences, and hopefully for the benefit of others too. (Here I am using the terms package and module interchangeably)

In answer to the question, yes the accepted answer would be:

npm list -g --depth=0

You might wish to check for a particular module installed globally, on *nix systems / when grep available. This is particularly useful when checking what version of a module you are using (globally installed, just remove the -g flag if checking a local module):

npm list -g --depth=0 | grep <module_name>

If you'd like to see all available (remote) versions for a particular module, then do:

npm view <module_name> versions

Note, versions is plural. This will give you the full listing of versions to choose from.

For latest remote version:

npm view <module_name> version  

Note, version is singular.

To find out which packages need to be updated, you can use

npm outdated -g --depth=0

To update global packages, you can use

npm update -g <package>

To update all global packages, you can use:

npm update -g

(However, for npm versions less than 2.6.1, please also see this link as there is a special script that is recommended for globally updating all packages).

The above commands should work across NPM versions 1.3.x, 1.4.x, 2.x and 3.x

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

Where are $_SESSION variables stored?

As mentioned already, the contents are stored at the server. However the session is identified by a session-id, which is stored at the client and send with each request. Usually the session-id is stored in a cookie, but it can also be appended to urls. (That's the PHPSESSID query-parameter you some times see)

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

WebDriverException: Element is not clickable at point (x, y)

This is a typical org.openqa.selenium.WebDriverException which extends java.lang.RuntimeException.

The fields of this exception are :

  • BASE_SUPPORT_URL : protected static final java.lang.String BASE_SUPPORT_URL
  • DRIVER_INFO : public static final java.lang.String DRIVER_INFO
  • SESSION_ID : public static final java.lang.String SESSION_ID

About your individual usecase, the error tells it all :

WebDriverException: Element is not clickable at point (x, y). Other element would receive the click 

It is clear from your code block that you have defined the wait as WebDriverWait wait = new WebDriverWait(driver, 10); but you are calling the click() method on the element before the ExplicitWait comes into play as in until(ExpectedConditions.elementToBeClickable).

Solution

The error Element is not clickable at point (x, y) can arise from different factors. You can address them by either of the following procedures:

1. Element not getting clicked due to JavaScript or AJAX calls present

Try to use Actions Class:

WebElement element = driver.findElement(By.id("navigationPageButton"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

2. Element not getting clicked as it is not within Viewport

Try to use JavascriptExecutor to bring the element within the Viewport:

WebElement myelement = driver.findElement(By.id("navigationPageButton"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement); 

3. The page is getting refreshed before the element gets clickable.

In this case induce ExplicitWait i.e WebDriverWait as mentioned in point 4.

4. Element is present in the DOM but not clickable.

In this case induce ExplicitWait with ExpectedConditions set to elementToBeClickable for the element to be clickable:

WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("navigationPageButton")));

5. Element is present but having temporary Overlay.

In this case, induce ExplicitWait with ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.

WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));

6. Element is present but having permanent Overlay.

Use JavascriptExecutor to send the click directly on the element.

WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);

In MVC, how do I return a string result?

public ActionResult GetAjaxValue()
{
   return Content("string value");
}

Raise an error manually in T-SQL to jump to BEGIN CATCH block

THROW (Transact-SQL)

Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2017.

Please refer the below link

T-SQL Throw Exception

How to calculate distance between two locations using their longitude and latitude value

public float getMesureLatLang(double lat,double lang) {

    Location loc1 = new Location("");
    loc1.setLatitude(getLatitute());// current latitude
    loc1.setLongitude(getLangitute());//current  Longitude

    Location loc2 = new Location("");
    loc2.setLatitude(lat);
    loc2.setLongitude(lang);

    return loc1.distanceTo(loc2);
 //  return distance(getLatitute(),getLangitute(),lat,lang);
}

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

In Winforms app, both methods:

System.Diagnostics.Debug.WriteLine("my string")

and

System.Console.WriteLine("my string")

write to the output window.

In AspNetCore app, only System.Diagnostics.Debug.WriteLine("my string") writes to the output window.

Get specific ArrayList item

Time to familiarize yourself with the ArrayList API and more:

ArrayList at Java 6 API Documentation

For your immediate question:

mainList.get(3);

Binding Listbox to List<object> in WinForms

There are two main routes here:

1: listBox1.DataSource = yourList;

Do any manipulation (Add/Delete) to yourList and Rebind.
Set DisplayMember and ValueMember to control what is shown.

2: listBox1.Items.AddRange(yourList.ToArray());

(or use a for-loop to do Items.Add(...))

You can control Display by overloading ToString() of the list objects or by implementing the listBox1.Format event.