Programs & Examples On #Class attribute

Xpath: select div that contains class AND whose specific child element contains text

To find a div of a certain class that contains a span at any depth containing certain text, try:

//div[contains(@class, 'measure-tab') and contains(.//span, 'someText')]

That said, this solution looks extremely fragile. If the table happens to contain a span with the text you're looking for, the div containing the table will be matched, too. I'd suggest to find a more robust way of filtering the elements. For example by using IDs or top-level document structure.

how to use ng-option to set default value of select element

If anyone is running into the default value occasionally being not populated on the page in Chrome, IE 10/11, Firefox -- try adding this attribute to your input/select field checking for the populated variable in the HTML, like so:

<input data-ng-model="vm.x" data-ng-if="vm.x !== '' && vm.x !== undefined && vm.x !== null" />

SQL Query to add a new column after an existing column in SQL Server 2005

According to my research there is no way to do this exactly the way you want. You can manually re-create the table and copy the data, or SSMS can (and will) do this for you (when you drag and drop a column to a different order, it does this). In fact it souldn't matter what order the columns are... As an alternative solution you can select the data you want in the order you desired. For example, instead of using asterisk (*) in select, specify the column names in some order... Lets say MyTable has col1, col2, col3, colNew columns.

Instead of:

SELECT * FROM MyTable

You can use:

SELECT col1, colNew, col2, col3 FROM MyTable

How to open an elevated cmd using command line for Windows?

According to documentation, the Windows security model...

does not grant administrative privileges at all times. Even administrators run under standard privileges when they perform non-administrative tasks that do not require elevated privileges.

You have the Create this task with administrative privileges option in the Create new task dialog (Task Manager > File > Run new task), but there is no built-in way to effectively elevate privileges using the command line.

However, there are some third party tools (internally relying on Windows APIs) you can use to elevate privileges from the command line:

NirCmd:

  1. Download it and unzip it.
  2. nircmdc elevate cmd

windosu:

  1. Install it: npm install -g windosu (requires node.js installed)
  2. sudo cmd

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

In my.cnf file check below 2 steps.

  • check this value -

    old_passwords=0;

    it should be 0.

  • check this also-

    [mysqld] default_authentication_plugin= mysql_native_password Another value to check is to make sure

    [mysqld] section should be like this.

Angular 2 Cannot find control with unspecified name attribute on formArrays

Only WinMerge made me find it (by comparison with a version that works). I had a case problem on formGroupName. Brackets around this word can lead to the same problem.

what is the use of xsi:schemaLocation?

If you go into any of those locations, then you will find what is defined in those schema. For example, it tells you what is the data type of the ini-method key words value.

Kubernetes service external ip pending

Delete existing service and create a same new service solved my problems. My problems is that the loading balancing IP I defines is used so that external endpoint is pending. When I changed a new load balancing IP it still couldn't work.

Finally, delete existing service and create a new one solved my problem.

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

You can do it with a separate UPDATE statement

UPDATE report.TEST target
SET    is Deleted = 'Y'
WHERE  NOT EXISTS (SELECT 1
                   FROM   main.TEST source
                   WHERE  source.ID = target.ID);

I don't know of any way to integrate this into your MERGE statement.

What does it mean to bind a multicast (UDP) socket?

It is also very important to distinguish a SENDING multicast socket from a RECEIVING multicast socket.

I agree with all the answers above regarding RECEIVING multicast sockets. The OP noted that binding a RECEIVING socket to an interface did not help. However, it is necessary to bind a multicast SENDING socket to an interface.

For a SENDING multicast socket on a multi-homed server, it is very important to create a separate socket for each interface you want to send to. A bound SENDING socket should be created for each interface.

  // This is a fix for that bug that causes Servers to pop offline/online.
  // Servers will intermittently pop offline/online for 10 seconds or so.
  // The bug only happens if the machine had a DHCP gateway, and the gateway is no longer accessible.
  // After several minutes, the route to the DHCP gateway may timeout, at which
  // point the pingponging stops.
  // You need 3 machines, Client machine, server A, and server B
  // Client has both ethernets connected, and both ethernets receiving CITP pings (machine A pinging to en0, machine B pinging to en1)
  // Now turn off the ping from machine B (en1), but leave the network connected.
  // You will notice that the machine transmitting on the interface with
  // the DHCP gateway will fail sendto() with errno 'No route to host'
  if ( theErr == 0 )
  {
     // inspired by 'ping -b' option in man page:      
     //      -b boundif
     //             Bind the socket to interface boundif for sending.
     struct sockaddr_in bindInterfaceAddr;
     bzero(&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     bindInterfaceAddr.sin_len = sizeof(bindInterfaceAddr);
     bindInterfaceAddr.sin_family = AF_INET;
     bindInterfaceAddr.sin_addr.s_addr = htonl(interfaceipaddr);
     bindInterfaceAddr.sin_port = 0; // Allow the kernel to choose a random port number by passing in 0 for the port.
     theErr = bind(mSendSocketID, (struct sockaddr *)&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     struct sockaddr_in serverAddress;
     int namelen = sizeof(serverAddress);  
     if (getsockname(mSendSocketID, (struct sockaddr *)&serverAddress, (socklen_t *)&namelen) < 0) {
        DLogErr(@"ERROR Publishing service... getsockname err");
     }
     else
     {
        DLog( @"socket %d bind, %@ port %d", mSendSocketID, [NSString stringFromIPAddress:htonl(serverAddress.sin_addr.s_addr)], htons(serverAddress.sin_port) );
     }

Without this fix, multicast sending will intermittently get sendto() errno 'No route to host'. If anyone can shed light on why unplugging a DHCP gateway causes Mac OS X multicast SENDING sockets to get confused, I would love to hear it.

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

This error can also be caused if the jar file that contains the XSD you require is not included in your deployed class path.

Make sure the dependencies are available in your container.

How to do while loops with multiple conditions

use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish

while 1:
  if condition1 and condition2:
      break
  ...
  ...
  if condition3: break
  ...
  ...

C++ printing spaces or tabs given a user input integer

You just need a loop that iterates the number of times given by n and prints a space each time. This would do:

while (n--) {
  std::cout << ' ';
}

How to create a GUID/UUID in Python

Copied from : https://docs.python.org/2/library/uuid.html (Since the links posted were not active and they keep updating)

>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'

>>> # get the raw 16 bytes of the UUID
>>> x.bytes
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')

Open youtube video in Fancybox jquery

$("a.more").click(function() {
                 $.fancybox({
                  'padding'             : 0,
                  'autoScale'   : false,
                  'transitionIn'        : 'none',
                  'transitionOut'       : 'none',
                  'title'               : this.title,
                  'width'               : 680,
                  'height'              : 495,
                  'href'                : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                  'type'                : 'swf',    // <--add a comma here
                  'swf'                 : {'allowfullscreen':'true'} // <-- flashvars here
                  });
                 return false;

            }); 

Convert a date format in epoch

You can also use the new Java 8 API

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class StackoverflowTest{
    public static void main(String args[]){
        String strDate = "Jun 13 2003 23:11:52.454 UTC";
        DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
        ZonedDateTime     zdt  = ZonedDateTime.parse(strDate,dtf);        
        System.out.println(zdt.toInstant().toEpochMilli());  // 1055545912454  
    }
}

The DateTimeFormatter class replaces the old SimpleDateFormat. You can then create a ZonedDateTime from which you can extract the desired epoch time.

The main advantage is that you are now thread safe.

Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.

how to log in to mysql and query the database from linux terminal

To stop or start mysql on most linux systems the following should work:

/etc/init.d/mysqld stop

/etc/init.d/mysqld start

The other answers look good for accessing the mysql client from the command line.

Good luck!

Python truncate a long string

If you are using Python 3.4+, you can use textwrap.shorten from the standard library:

Collapse and truncate the given text to fit in the given width.

First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is returned. Otherwise, enough words are dropped from the end so that the remaining words plus the placeholder fit within width:

>>> textwrap.shorten("Hello  world!", width=12)
'Hello world!'
>>> textwrap.shorten("Hello  world!", width=11)
'Hello [...]'
>>> textwrap.shorten("Hello world", width=10, placeholder="...")
'Hello...'

Screen width in React Native

April 10th 2020 Answer:

The suggested answer using Dimensions is now discouraged. See: https://reactnative.dev/docs/dimensions

The recommended approach is using the useWindowDimensions hook in React; https://reactnative.dev/docs/usewindowdimensions which uses a hook based API and will also update your value when the screen value changes (on screen rotation for example):

import {useWindowDimensions} from 'react-native';

const windowWidth = useWindowDimensions().width;
const windowHeight = useWindowDimensions().height;

Note: useWindowDimensions is only available from React Native 0.61.0: https://reactnative.dev/blog/2019/09/18/version-0.61

How do I remove all null and empty string values from an object?

You're deleting sjonObj.key, literally. You need to use array access notation:

delete sjonObj[key];

However, that will also delete where value is equal to 0, since you're not using strict comparison. Use === instead:

$.each(sjonObj, function(key, value){
    if (value === "" || value === null){
        delete sjonObj[key];
    }
});

However, this will only walk the object shallowly. To do it deeply, you can use recursion:

(function filter(obj) {
    $.each(obj, function(key, value){
        if (value === "" || value === null){
            delete obj[key];
        } else if (Object.prototype.toString.call(value) === '[object Object]') {
            filter(value);
        } else if ($.isArray(value)) {
            $.each(value, function (k,v) { filter(v); });
        }
    });
})(sjonObj);

_x000D_
_x000D_
var sjonObj = {_x000D_
  "executionMode": "SEQUENTIAL",_x000D_
  "coreTEEVersion": "3.3.1.4_RC8",_x000D_
  "testSuiteId": "yyy",_x000D_
  "testSuiteFormatVersion": "1.0.0.0",_x000D_
  "testStatus": "IDLE",_x000D_
  "reportPath": "",_x000D_
  "startTime": 0,_x000D_
  "durationBetweenTestCases": 20,_x000D_
  "endTime": 0,_x000D_
  "lastExecutedTestCaseId": 0,_x000D_
  "repeatCount": 0,_x000D_
  "retryCount": 0,_x000D_
  "fixedTimeSyncSupported": false,_x000D_
  "totalRepeatCount": 0,_x000D_
  "totalRetryCount": 0,_x000D_
  "summaryReportRequired": "true",_x000D_
  "postConditionExecution": "ON_SUCCESS",_x000D_
  "testCaseList": [_x000D_
    {_x000D_
      "executionMode": "SEQUENTIAL",_x000D_
      "commandList": [_x000D_
        _x000D_
      ],_x000D_
      "testCaseList": [_x000D_
        _x000D_
      ],_x000D_
      "testStatus": "IDLE",_x000D_
      "boundTimeDurationForExecution": 0,_x000D_
      "startTime": 0,_x000D_
      "endTime": 0,_x000D_
      "label": null,_x000D_
      "repeatCount": 0,_x000D_
      "retryCount": 0,_x000D_
      "totalRepeatCount": 0,_x000D_
      "totalRetryCount": 0,_x000D_
      "testCaseId": "a",_x000D_
      "summaryReportRequired": "false",_x000D_
      "postConditionExecution": "ON_SUCCESS"_x000D_
    },_x000D_
    {_x000D_
      "executionMode": "SEQUENTIAL",_x000D_
      "commandList": [_x000D_
        _x000D_
      ],_x000D_
      "testCaseList": [_x000D_
        {_x000D_
          "executionMode": "SEQUENTIAL",_x000D_
          "commandList": [_x000D_
            {_x000D_
              "commandParameters": {_x000D_
                "serverAddress": "www.ggp.com",_x000D_
                "echoRequestCount": "",_x000D_
                "sendPacketSize": "",_x000D_
                "interval": "",_x000D_
                "ttl": "",_x000D_
                "addFullDataInReport": "True",_x000D_
                "maxRTT": "",_x000D_
                "failOnTargetHostUnreachable": "True",_x000D_
                "failOnTargetHostUnreachableCount": "",_x000D_
                "initialDelay": "",_x000D_
                "commandTimeout": "",_x000D_
                "testDuration": ""_x000D_
              },_x000D_
              "commandName": "Ping",_x000D_
              "testStatus": "IDLE",_x000D_
              "label": "",_x000D_
              "reportFileName": "tc_2-tc_1-cmd_1_Ping",_x000D_
              "endTime": 0,_x000D_
              "startTime": 0,_x000D_
              "repeatCount": 0,_x000D_
              "retryCount": 0,_x000D_
              "totalRepeatCount": 0,_x000D_
              "totalRetryCount": 0,_x000D_
              "postConditionExecution": "ON_SUCCESS",_x000D_
              "detailReportRequired": "true",_x000D_
              "summaryReportRequired": "true"_x000D_
            }_x000D_
          ],_x000D_
          "testCaseList": [_x000D_
            _x000D_
          ],_x000D_
          "testStatus": "IDLE",_x000D_
          "boundTimeDurationForExecution": 0,_x000D_
          "startTime": 0,_x000D_
          "endTime": 0,_x000D_
          "label": null,_x000D_
          "repeatCount": 0,_x000D_
          "retryCount": 0,_x000D_
          "totalRepeatCount": 0,_x000D_
          "totalRetryCount": 0,_x000D_
          "testCaseId": "dd",_x000D_
          "summaryReportRequired": "false",_x000D_
          "postConditionExecution": "ON_SUCCESS"_x000D_
        }_x000D_
      ],_x000D_
      "testStatus": "IDLE",_x000D_
      "boundTimeDurationForExecution": 0,_x000D_
      "startTime": 0,_x000D_
      "endTime": 0,_x000D_
      "label": null,_x000D_
      "repeatCount": 0,_x000D_
      "retryCount": 0,_x000D_
      "totalRepeatCount": 0,_x000D_
      "totalRetryCount": 0,_x000D_
      "testCaseId": "b",_x000D_
      "summaryReportRequired": "false",_x000D_
      "postConditionExecution": "ON_SUCCESS"_x000D_
    }_x000D_
  ]_x000D_
};_x000D_
_x000D_
(function filter(obj) {_x000D_
    $.each(obj, function(key, value){_x000D_
        if (value === "" || value === null){_x000D_
            delete obj[key];_x000D_
        } else if (Object.prototype.toString.call(value) === '[object Object]') {_x000D_
            filter(value);_x000D_
        } else if (Array.isArray(value)) {_x000D_
            value.forEach(function (el) { filter(el); });_x000D_
        }_x000D_
    });_x000D_
})(sjonObj);_x000D_
_x000D_
console.log(sjonObj)
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


Note that if you're willing to use a library like lodash/underscore.js, you can use _.pick instead. However, you will still need to use recursion to filter deeply, since neither library provides a deep filter function.

sjonObj = (function filter(obj) {
    var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });
    return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });
})(sjonObj);

This variant has the added advantage of leaving the original object unmodified, but it does create an entirely new copy, which would be less efficient if you don't need the original object.

_x000D_
_x000D_
var sjonObj = {_x000D_
  "executionMode": "SEQUENTIAL",_x000D_
  "coreTEEVersion": "3.3.1.4_RC8",_x000D_
  "testSuiteId": "yyy",_x000D_
  "testSuiteFormatVersion": "1.0.0.0",_x000D_
  "testStatus": "IDLE",_x000D_
  "reportPath": "",_x000D_
  "startTime": 0,_x000D_
  "durationBetweenTestCases": 20,_x000D_
  "endTime": 0,_x000D_
  "lastExecutedTestCaseId": 0,_x000D_
  "repeatCount": 0,_x000D_
  "retryCount": 0,_x000D_
  "fixedTimeSyncSupported": false,_x000D_
  "totalRepeatCount": 0,_x000D_
  "totalRetryCount": 0,_x000D_
  "summaryReportRequired": "true",_x000D_
  "postConditionExecution": "ON_SUCCESS",_x000D_
  "testCaseList": [_x000D_
    {_x000D_
      "executionMode": "SEQUENTIAL",_x000D_
      "commandList": [_x000D_
        _x000D_
      ],_x000D_
      "testCaseList": [_x000D_
        _x000D_
      ],_x000D_
      "testStatus": "IDLE",_x000D_
      "boundTimeDurationForExecution": 0,_x000D_
      "startTime": 0,_x000D_
      "endTime": 0,_x000D_
      "label": null,_x000D_
      "repeatCount": 0,_x000D_
      "retryCount": 0,_x000D_
      "totalRepeatCount": 0,_x000D_
      "totalRetryCount": 0,_x000D_
      "testCaseId": "a",_x000D_
      "summaryReportRequired": "false",_x000D_
      "postConditionExecution": "ON_SUCCESS"_x000D_
    },_x000D_
    {_x000D_
      "executionMode": "SEQUENTIAL",_x000D_
      "commandList": [_x000D_
        _x000D_
      ],_x000D_
      "testCaseList": [_x000D_
        {_x000D_
          "executionMode": "SEQUENTIAL",_x000D_
          "commandList": [_x000D_
            {_x000D_
              "commandParameters": {_x000D_
                "serverAddress": "www.ggp.com",_x000D_
                "echoRequestCount": "",_x000D_
                "sendPacketSize": "",_x000D_
                "interval": "",_x000D_
                "ttl": "",_x000D_
                "addFullDataInReport": "True",_x000D_
                "maxRTT": "",_x000D_
                "failOnTargetHostUnreachable": "True",_x000D_
                "failOnTargetHostUnreachableCount": "",_x000D_
                "initialDelay": "",_x000D_
                "commandTimeout": "",_x000D_
                "testDuration": ""_x000D_
              },_x000D_
              "commandName": "Ping",_x000D_
              "testStatus": "IDLE",_x000D_
              "label": "",_x000D_
              "reportFileName": "tc_2-tc_1-cmd_1_Ping",_x000D_
              "endTime": 0,_x000D_
              "startTime": 0,_x000D_
              "repeatCount": 0,_x000D_
              "retryCount": 0,_x000D_
              "totalRepeatCount": 0,_x000D_
              "totalRetryCount": 0,_x000D_
              "postConditionExecution": "ON_SUCCESS",_x000D_
              "detailReportRequired": "true",_x000D_
              "summaryReportRequired": "true"_x000D_
            }_x000D_
          ],_x000D_
          "testCaseList": [_x000D_
            _x000D_
          ],_x000D_
          "testStatus": "IDLE",_x000D_
          "boundTimeDurationForExecution": 0,_x000D_
          "startTime": 0,_x000D_
          "endTime": 0,_x000D_
          "label": null,_x000D_
          "repeatCount": 0,_x000D_
          "retryCount": 0,_x000D_
          "totalRepeatCount": 0,_x000D_
          "totalRetryCount": 0,_x000D_
          "testCaseId": "dd",_x000D_
          "summaryReportRequired": "false",_x000D_
          "postConditionExecution": "ON_SUCCESS"_x000D_
        }_x000D_
      ],_x000D_
      "testStatus": "IDLE",_x000D_
      "boundTimeDurationForExecution": 0,_x000D_
      "startTime": 0,_x000D_
      "endTime": 0,_x000D_
      "label": null,_x000D_
      "repeatCount": 0,_x000D_
      "retryCount": 0,_x000D_
      "totalRepeatCount": 0,_x000D_
      "totalRetryCount": 0,_x000D_
      "testCaseId": "b",_x000D_
      "summaryReportRequired": "false",_x000D_
      "postConditionExecution": "ON_SUCCESS"_x000D_
    }_x000D_
  ]_x000D_
};_x000D_
_x000D_
sjonObj = (function filter(obj) {_x000D_
    var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });_x000D_
    return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });_x000D_
})(sjonObj);_x000D_
_x000D_
console.log(sjonObj);
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
_x000D_
_x000D_
_x000D_

How to find out what the date was 5 days ago?

General algorithms for date manipulation convert dates to and from Julian Day Numbers. Here is a link to a description of such algorithms, a description of the best algorithms currently known, and the mathematical proofs of each of them: http://web.archive.org/web/20140910060704/http://mysite.verizon.net/aesir_research/date/date0.htm

How to zero pad a sequence of integers in bash so that all have the same width?

This will work also:

for i in {0..9}{0..9}{0..9}{0..9}
do
  echo "$i"
done

Check if a specific tab page is selected (active)

To check if a specific tab page is the currently selected page of a tab control is easy; just use the SelectedTab property of the tab control:

if (tabControl1.SelectedTab == someTabPage)
{
// Do stuff here...
}

This is more useful if the code is executed based on some event other than the tab page being selected (in which case SelectedIndexChanged would be a better choice).

For example I have an application that uses a timer to regularly poll stuff over TCP/IP connection, but to avoid unnecessary TCP/IP traffic I only poll things that update GUI controls in the currently selected tab page.

CSS /JS to prevent dragging of ghost image?

The be-all-end-all, for no selecting or dragging, with all browser prefixes:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
user-select: none;

-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
-ms-user-drag: none;
user-drag: none;

You can also set the draggable attribute to false. You can do this with inline HTML: draggable="false", with Javascript: elm.draggable = false, or with jQuery: elm.attr('draggable', false).

You can also handle the onmousedown function to return false. You can do this with inline HTML: onmousedown="return false", with Javascript: elm.onmousedown=()=>return false;, or with jQuery: elm.mousedown(()=>return false)

Adding additional data to select options using jQuery

To store another value in select options:

$("#select").append('<option value="4">another</option>')

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

Here's 2 sorts I came up with my roommate in college

1) Check the order 2) Maybe a miracle happened, go to 1

and

1) check if it is in order, if not 2) put each element into a packet and bounce it off a distant server back to yourself. Some of those packets will return in a different order, so go to 1

How do I create a list of random numbers without duplicates?

If you need to sample extremely large numbers, you cannot use range

random.sample(range(10000000000000000000000000000000), 10)

because it throws:

OverflowError: Python int too large to convert to C ssize_t

Also, if random.sample cannot produce the number of items you want due to the range being too small

 random.sample(range(2), 1000)

it throws:

 ValueError: Sample larger than population

This function resolves both problems:

import random

def random_sample(count, start, stop, step=1):
    def gen_random():
        while True:
            yield random.randrange(start, stop, step)

    def gen_n_unique(source, n):
        seen = set()
        seenadd = seen.add
        for i in (i for i in source() if i not in seen and not seenadd(i)):
            yield i
            if len(seen) == n:
                break

    return [i for i in gen_n_unique(gen_random,
                                    min(count, int(abs(stop - start) / abs(step))))]

Usage with extremely large numbers:

print('\n'.join(map(str, random_sample(10, 2, 10000000000000000000000000000000))))

Sample result:

7822019936001013053229712669368
6289033704329783896566642145909
2473484300603494430244265004275
5842266362922067540967510912174
6775107889200427514968714189847
9674137095837778645652621150351
9969632214348349234653730196586
1397846105816635294077965449171
3911263633583030536971422042360
9864578596169364050929858013943

Usage where the range is smaller than the number of requested items:

print(', '.join(map(str, random_sample(100000, 0, 3))))

Sample result:

2, 0, 1

It also works with with negative ranges and steps:

print(', '.join(map(str, random_sample(10, 10, -10, -2))))
print(', '.join(map(str, random_sample(10, 5, -5, -2))))

Sample results:

2, -8, 6, -2, -4, 0, 4, 10, -6, 8
-3, 1, 5, -1, 3

How do I run a spring boot executable jar in a Production environment?

I start applications that I want to run persistently or at least semi-permanently via screen -dmS NAME /path/to/script. As far as I am informed this is the most elegant solution.

Setting active profile and config location from command line in spring boot

I think your problem is likely related to your spring.config.location not ending the path with "/".

Quote the docs

If spring.config.location contains directories (as opposed to files) they should end in / (and will be appended with the names generated from spring.config.name before being loaded).

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-application-property-files

Using DISTINCT inner join in SQL

SELECT DISTINCT C.valueC 
FROM C 
  LEFT JOIN B ON C.id = B.lookupC
  LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.


EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

How can I debug a .BAT script?

I found 'running steps' (win32) software doing exactly what I was looking for: http://www.steppingsoftware.com/

You can load a bat file, place breakpoints / start stepping through it while seeing the output and environment variables.

The evaluation version only allows to step through 50 lines... Does anyone have a free alternative with similar functionality?

How do I divide so I get a decimal value?

int a = 3;
int b = 2;
float c = ((float)a)/b

PHP create key => value pairs within a foreach

Create key-value pairs within a foreach like this:

function createOfferUrlArray($Offer) {
    $offerArray = array();

    foreach ($Offer as $key => $value) {
        $offerArray[$key] = $value[4];
    }

    return $offerArray;
}

How to call window.alert("message"); from C#?

if you are using ajax in your page that require script manager Page.ClientScript
will not work, Try this and it would do the work:

ScriptManager.RegisterClientScriptBlock(this, GetType(),
            "alertMessage", @"alert('your Message ')", true);

jQuery, get ID of each element in a class using .each?

Try this, replacing .myClassName with the actual name of the class (but keep the period at the beginning).

$('.myClassName').each(function() {
    alert( this.id );
});

So if the class is "test", you'd do $('.test').each(func....

This is the specific form of .each() that iterates over a jQuery object.

The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t.

Using that form of $.each(), you would need to do it like this:

$.each($('.myClassName'), function() {
    alert( this.id );
});

...which will have the same result as the example above.

How to add Action bar options menu in Android Fragments

in AndroidManifest.xml set theme holo like this:

<activity
android:name="your Fragment or activity"
android:label="@string/xxxxxx"
android:theme="@android:style/Theme.Holo" >

How to change the text of a button in jQuery?

it's work for me html:

<button type="button" class="btn btn-primary" id="btnSaveSchedule">abc</button>

js

$("#btnSaveSchedule").text("new value");

How can I check if a URL exists via PHP?

cURL can return HTTP code I don’t think all that extra code is necessary?

function urlExists($url=NULL)
    {
        if($url == NULL) return false;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch); 
        if($httpcode>=200 && $httpcode<300){
            return true;
        } else {
            return false;
        }
    }

Root user/sudo equivalent in Cygwin?

Being unhappy with the available solution, I adopted nu774's script to add security and make it easier to setup and use. The project is available on Github

To use it, just download cygwin-sudo.py and run it via python3 cygwin-sudo.py **yourcommand**.

You can set up an alias for convenience:

alias sudo="python3 /path-to-cygwin-sudo/cygwin-sudo.py"

How to type a new line character in SQL Server Management Studio

In SSMS, you can't print new line with select, just using PRINT instead

DECLARE @text NVARCHAR(100)
SET @text = concat(N'This is line 1.', CHAR(10), N'This is line 2.')
PRINT @text

Toggle show/hide on click with jQuery

this will work for u

   $("#button-name").click(function(){
        $('#toggle-id').slideToggle('slow');
    });

Sleeping in a batch file

Over at Server Fault, a similar question was asked, and the solution there was:

choice /d y /t 5 > nul

Java: Sending Multiple Parameters to Method

Suppose you have void method that prints many objects;

public static void print( Object... values){
   for(Object c : values){
      System.out.println(c);
   }
}

Above example I used vararge as an argument that accepts values from 0 to N.

From comments: What if 2 strings and 5 integers ??

Answer:

print("string1","string2",1,2,3,4,5);

SQL - IF EXISTS UPDATE ELSE INSERT INTO

  1. Create a UNIQUE constraint on your subs_email column, if one does not already exist:

    ALTER TABLE subs ADD UNIQUE (subs_email)
    
  2. Use INSERT ... ON DUPLICATE KEY UPDATE:

    INSERT INTO subs
      (subs_name, subs_email, subs_birthday)
    VALUES
      (?, ?, ?)
    ON DUPLICATE KEY UPDATE
      subs_name     = VALUES(subs_name),
      subs_birthday = VALUES(subs_birthday)
    

You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com

  1. Note that I have used parameter placeholders in the place of string literals, as one really should be using parameterised statements to defend against SQL injection attacks.

How to detect if a browser is Chrome using jQuery?

if(navigator.vendor.indexOf('Goog') > -1){
  //Your code here
}

Regular expression for 10 digit number without any special characters

Use this regular expression to match ten digits only:

@"^\d{10}$"

To find a sequence of ten consecutive digits anywhere in a string, use:

@"\d{10}"

Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits and not more you can use negative lookarounds:

@"(?<!\d)\d{10}(?!\d)"

When to use cla(), clf() or close() for clearing a plot in matplotlib?

plt.cla() means clear current axis

plt.clf() means clear current figure

also, there's plt.gca() (get current axis) and plt.gcf() (get current figure)

Read more here: Matplotlib, Pyplot, Pylab etc: What's the difference between these and when to use each?

Bootstrap 4: Multilevel Dropdown Inside Navigation

The following is MultiLevel dropdown based on bootstrap4. I tried it was according to the bootstrap4 basic dropdown.

_x000D_
_x000D_
.dropdown-submenu{_x000D_
    position: relative;_x000D_
}_x000D_
.dropdown-submenu a::after{_x000D_
    transform: rotate(-90deg);_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 40%;_x000D_
}_x000D_
.dropdown-submenu:hover .dropdown-menu, .dropdown-submenu:focus .dropdown-menu{_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    position: absolute !important;_x000D_
    margin-top: -30px;_x000D_
    left: 100%;_x000D_
}_x000D_
@media (max-width: 992px) {_x000D_
    .dropdown-menu{_x000D_
        width: 50%;_x000D_
    }_x000D_
    .dropdown-menu .dropdown-submenu{_x000D_
        width: auto;_x000D_
    }_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link 1</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown link_x000D_
        </a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
          <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
          <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
          <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" data-toggle="dropdown" href="#">Something else here</a>_x000D_
            <ul class="dropdown-menu">_x000D_
              <a class="dropdown-item" href="#">A</a>_x000D_
              <a class="dropdown-item" href="#">b</a>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to add an element to a list?

import json

myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}]}

myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}

How to set an button align-right with Bootstrap?

UPDATE: For Bootstrap 5

The class name is now "float-end" instead of "pull-right"

<div class="alert alert-info clearfix">
    <a href="#" class="alert-link">
      Summary:Its some description.......testtesttest
    </a> 
    <button type="button" class="btn btn-primary btn-lg float-end">
      Large button
    </button>
</div>

For Bootstrap 4 and under

Just add a simple pull-right class to the button, and make sure the container div is clearfixed:

<div class="alert alert-info clearfix">
    <a href="#" class="alert-link">
      Summary:Its some description.......testtesttest
    </a> 
    <button type="button" class="btn btn-primary btn-lg pull-right">
      Large button
    </button>
</div>

How do I find the parent directory in C#?

Directory.GetParent is probably a better answer, but for completeness there's a different method that takes string and returns string: Path.GetDirectoryName.

string parent = System.IO.Path.GetDirectoryName(str_directory);

Make docker use IPv4 for port binding

As @daniel-t points out in the comment: github.com/docker/docker/issues/2174 is about showing binding only to IPv6 in netstat, but that is not an issue. As that github issues states:

When setting up the proxy, Docker requests the loopback address '127.0.0.1', Linux realises this is an address that exists in IPv6 (as ::0) and opens on both (but it is formally an IPv6 socket). When you run netstat it sees this and tells you it is an IPv6 - but it is still listening on IPv4. If you have played with your settings a little, you may have disabled this trick Linux does - by setting net.ipv6.bindv6only = 1.

In other words, just because you see it as IPv6 only, it is still able to communicate on IPv4 unless you have IPv6 set to only bind on IPv6 with the net.ipv6.bindv6only setting. To be clear, net.ipv6.bindv6only should be 0 - you can run sysctl net.ipv6.bindv6only to verify.

CSS On hover show another element

It is indeed possible with the following code

 <div href="#" id='a'>
     Hover me
 </div>

<div id='b'>
    Show me
</div>

and css

#a {
  display: block;
}

#a:hover + #b {
  display:block;
}

#b {
  display:none;
  }

Now by hovering on element #a shows element #b.

How to set a session variable when clicking a <a> link

In HTML:

<a href="index.php?link=home" name="home">home</a>

Then in PHP:

if(isset($_GET['link'])){$_SESSION['link'] = $_GET['link'];}

How to insert the current timestamp into MySQL database using a PHP insert query

Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.

You can modify your query to use double quotes at the beginning and end, and single quotes around $somename:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";

Prevent content from expanding grid items

The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:


.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;  
}

.day-item-wrapper {
  position: relative;
}

.day-item {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 10px;

  background: rgba(0,0,0,0.1);
}

https://codepen.io/bjnsn/pen/vYYVPZv

Add Auto-Increment ID to existing table?

ALTER TABLE users CHANGE id int( 30 ) NOT NULL AUTO_INCREMENT

the integer parameter is based on my default sql setting have a nice day

Set NA to 0 in R

A solution using mutate_all from dplyr in case you want to add that to your dplyr pipeline:

library(dplyr)
df %>%
  mutate_all(funs(ifelse(is.na(.), 0, .)))

Result:

   A B C
1  0 0 0
2  1 0 0
3  2 0 2
4  3 0 5
5  0 0 2
6  0 0 1
7  1 0 1
8  2 0 5
9  3 0 2
10 0 0 4
11 0 0 3
12 1 0 5
13 2 0 5
14 3 0 0
15 0 0 1

If in any case you only want to replace the NA's in numeric columns, which I assume it might be the case in modeling, you can use mutate_if:

library(dplyr)
df %>%
  mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))

or in base R:

replace(is.na(df), 0)

Result:

   A    B C
1  0    0 0
2  1 <NA> 0
3  2    0 2
4  3 <NA> 5
5  0    0 2
6  0 <NA> 1
7  1    0 1
8  2 <NA> 5
9  3    0 2
10 0 <NA> 4
11 0    0 3
12 1 <NA> 5
13 2    0 5
14 3 <NA> 0
15 0    0 1

Update

with dplyr 1.0.0, across is introduced:

library(dplyr)
# Replace `NA` for all columns
df %>%
  mutate(across(everything(), ~ ifelse(is.na(.), 0, .)))

# Replace `NA` for numeric columns
df %>%
  mutate(across(where(is.numeric), ~ ifelse(is.na(.), 0, .)))

Data:

set.seed(123)
df <- data.frame(A=rep(c(0:3, NA), 3), 
                 B=rep(c("0", NA), length.out = 15), 
                 C=sample(c(0:5, NA), 15, replace = TRUE))

How to get value of Radio Buttons?

An alterntive is to use an enum and a component class that extends the standard RadioButton.

public enum Genders
{
    Male,
    Female
}

[ToolboxBitmap(typeof(RadioButton))]
public partial class GenderRadioButton : RadioButton
{
    public GenderRadioButton()
    {
        InitializeComponent();
    }

    public GenderRadioButton (IContainer container)
    {
        container.Add(this);

        InitializeComponent();
    }

    public Genders gender{ get; set; }
}

Use a common event handler for the GenderRadioButtons

private void Gender_CheckedChanged(Object sender, EventArgs e)
{
    if (((RadioButton)sender).Checked)
    {
        //get selected value
        Genders myGender = ((GenderRadioButton)sender).Gender;
        //get the name of the enum value
        string GenderName = Enum.GetName(typeof(Genders ), myGender);
        //do any work required when you change gender
        switch (myGender)
        {
            case Genders.Male:
                break;
            case Genders.Female:
                break;
            default:
                break;
        }
    }
}

Creating folders inside a GitHub repository without using Git

You can also just enter the website and:

  1. Choose a repository you have write access to (example URL)
  2. Click "Upload files"
  3. Drag and drop a folder with files into the "Drag files here to add them to your repository" area.

The same limitation applies here: the folder must contain at least one file inside it.

Excel function to get first word from sentence in other cell

If you want to cater to 1-word cell, use this... based upon astander's

=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)

How do I update pip itself from inside my virtual environment?

I was in a similar situation and wanted to update urllib3 package. What worked for me was:

pip3 install --upgrade --force-reinstall --ignore-installed urllib3==1.25.3

geom_smooth() what are the methods available?

The se argument from the example also isn't in the help or online documentation.

When 'se' in geom_smooth is set 'FALSE', the error shading region is not visible

How does Python return multiple values from a function?

Since the return statement in getName specifies multiple elements:

def getName(self):
   return self.first_name, self.last_name

Python will return a container object that basically contains them.

In this case, returning a comma separated set of elements creates a tuple. Multiple values can only be returned inside containers.

Let's use a simpler function that returns multiple values:

def foo(a, b):
    return a, b

You can look at the byte code generated by using dis.dis, a disassembler for Python bytecode. For comma separated values w/o any brackets, it looks like this:

>>> import dis
>>> def foo(a, b):
...     return a,b        
>>> dis.dis(foo)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_TUPLE              2
              9 RETURN_VALUE

As you can see the values are first loaded on the internal stack with LOAD_FAST and then a BUILD_TUPLE (grabbing the previous 2 elements placed on the stack) is generated. Python knows to create a tuple due to the commas being present.

You could alternatively specify another return type, for example a list, by using []. For this case, a BUILD_LIST is going to be issued following the same semantics as it's tuple equivalent:

>>> def foo_list(a, b):
...     return [a, b]
>>> dis.dis(foo_list)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_LIST               2
              9 RETURN_VALUE

The type of object returned really depends on the presence of brackets (for tuples () can be omitted if there's at least one comma). [] creates lists and {} sets. Dictionaries need key:val pairs.

To summarize, one actual object is returned. If that object is of a container type, it can contain multiple values giving the impression of multiple results returned. The usual method then is to unpack them directly:

>>> first_name, last_name = f.getName()
>>> print (first_name, last_name)

As an aside to all this, your Java ways are leaking into Python :-)

Don't use getters when writing classes in Python, use properties. Properties are the idiomatic way to manage attributes, for more on these, see a nice answer here.

How to dynamically create generic C# object using reflection?

Check out this article and this simple example. Quick translation of same to your classes ...

var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

Per your edit: For that case, you can do this ...

var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

To see where I came up with backtick1 for the name of the generic class, see this article.

Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:

Type type = typeof(IReadOnlyDictionary<,>);

for or while loop to do something n times

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

POST string to ASP.NET Web Api application - returns null

Web API works very nicely if you accept the fact that you are using HTTP. It's when you start trying to pretend that you are sending objects over the wire that it starts to get messy.

 public class TextController : ApiController
    {
        public HttpResponseMessage Post(HttpRequestMessage request) {

            var someText = request.Content.ReadAsStringAsync().Result;
            return new HttpResponseMessage() {Content = new StringContent(someText)};

        }

    }

This controller will handle a HTTP request, read a string out of the payload and return that string back.

You can use HttpClient to call it by passing an instance of StringContent. StringContent will be default use text/plain as the media type. Which is exactly what you are trying to pass.

    [Fact]
    public void PostAString()
    {

        var client = new HttpClient();

        var content = new StringContent("Some text");
        var response = client.PostAsync("http://oak:9999/api/text", content).Result;

        Assert.Equal("Some text",response.Content.ReadAsStringAsync().Result);

    }

JavaScript blob filename without link

Late, but since I had the same problem I add my solution:

function newFile(data, fileName) {
    var json = JSON.stringify(data);
    //IE11 support
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        let blob = new Blob([json], {type: "application/json"});
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {// other browsers
        let file = new File([json], fileName, {type: "application/json"});
        let exportUrl = URL.createObjectURL(file);
        window.location.assign(exportUrl);
        URL.revokeObjectURL(exportUrl);
    }
}

jQuery.active function

For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:

jQuery.ajaxPrefilter(function( options ) {
    options.global = true;
});

Keep in mind that you'll need a timeout on your JSONP request to catch failures.

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

Merge unequal dataframes and replace missing rows with 0

Another alternative with data.table.

EXAMPLE DATA

dt1 <- data.table(df1)
dt2 <- data.table(df2)
setkey(dt1,x)
setkey(dt2,x)

CODE

dt2[dt1,list(y=ifelse(is.na(y),0,y))]

How to convert String object to Boolean Object?

To get the boolean value of a String, try this:

public boolean toBoolean(String s) {
    try {
        return Boolean.parseBoolean(s); // Successfully converted String to boolean
    } catch(Exception e) {
        return null; // There was some error, so return null.
    }
}

If there is an error, it will return null. Example:

toBoolean("true"); // Returns true
toBoolean("tr.u;e"); // Returns null

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

How can I get the MAC and the IP address of a connected client in PHP?

I don't think you can get MAC address in PHP, but you can get IP from $_SERVER['REMOTE_ADDR'] variable.

How to get only filenames within a directory using c#?

You can simply use linq

Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));

Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.

Find out time it took for a python script to complete execution

Do you execute the script from the command line on Linux or UNIX? In that case, you could just use

time ./script.py

Linker Error C++ "undefined reference "

Your header file Hash.h declares "what class hash should look like", but not its implementation, which is (presumably) in some other source file we'll call Hash.cpp. By including the header in your main file, the compiler is informed of the description of class Hash when compiling the file, but not how class Hash actually works. When the linker tries to create the entire program, it then complains that the implementation (toHash::insert(int, char)) cannot be found.

The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:

g++ -o main Hash.cpp main.cpp

will create the main program called "main".

Textarea that can do syntax highlighting on the fly?

The only editor I know of that has syntax highlighting and a fallback to a textarea is Mozilla Bespin. Google around for embedding Bespin to see how to embed the editor. The only site I know of that uses this right now is the very alpha Mozilla Jetpack Gallery (in the submit a Jetpack page) and you may want to see how they include it.

There's also a blog post on embedding and reusing the Bespin editor that may help you.

How to change the default message of the required field in the popover of form-control in bootstrap?

Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"
 oninput="setCustomValidity('')"></input>

Here,

this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field

oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.

Convert Object to JSON string

Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

There was no endpoint listening at (url) that could accept the message

Another case I just had - when the request size is bigger than the request size set in IIS as a limit, then you can get that error too.

Check the IIS request limit and increase it if it's lower than you need. Here is how you can check and change the IIS request limit:

  1. Open the IIS
  2. Click your site and/or your mapped application
  3. Click on Feature view and click Request Filtering
  4. Click - Edit Feature Settings.

Edit Feature Settings

I just found also another thread in stack IIS 7.5 hosted WCF service throws EndpointNotFoundException with 404 only for large requests

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

In my case i kept getting the same error message. I use fedora. I solved it by doing:

sudo dnf install pycurl

This installed eveything that I needed for it to work.

SVN repository backup strategies

For hosted repositories you can since svn version 1.7 use svnrdump, which is analogous to svnadmin dump for local repositories. This article provides a nice walk-through, which essentially boils down to:

svnrdump dump /URL/to/remote/repository > myRepository.dump

After you have downloaded the dump file you can import it locally

svnadmin load /path/to/local/repository < myRepository.dump

or upload it to the host of your choice.

Disable developer mode extensions pop up in Chrome

I found something that will load user-packed extensions and works beautifully:

You'll still have to pack it in details for the problem extension, but after that you can turn off developer mode and load the packed CRX through this. You don't have to deal with signing it or anything.

https://chrome.google.com/webstore/detail/crosspilot/migomhggnppjdijnfkiimcpjgnhmnale?hl=en

Note: I'm not from their team, I've just been looking for an elegant solution for this for years.

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

Here is the pure HTML and CSS solution.

  1. We create a container box for navbar with position: fixed; height:100%;

  2. Then we create an inner box with height: 100%; overflow-y: scroll;

  3. Next, we put out content inside that box.

Here is the code:

_x000D_
_x000D_
.nav-box{_x000D_
        position: fixed;_x000D_
        border: 1px solid #0a2b1d;_x000D_
        height:100%;_x000D_
   }_x000D_
   .inner-box{_x000D_
        width: 200px;_x000D_
        height: 100%;_x000D_
        overflow-y: scroll;_x000D_
        border: 1px solid #0A246A;_x000D_
    }_x000D_
    .tabs{_x000D_
        border: 3px solid chartreuse;_x000D_
        color:darkred;_x000D_
    }_x000D_
    .content-box p{_x000D_
      height:50px;_x000D_
      text-align:center;_x000D_
    }
_x000D_
<div class="nav-box">_x000D_
  <div class="inner-box">_x000D_
    <div class="tabs"><p>Navbar content Start</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content End</p></div>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="content-box">_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link to jsFiddle:

How can I change IIS Express port for a site

Another fix for those who have IIS Installed:

Create a path on the IIS Server, and allocate your website/app there.

Go to propieties of the solution of the explorer, then in front of using the iisexpress from visual studio, make that vs uses your personal own IIS.

Solution Proprieties

Best way to structure a tkinter application?

This isn't a bad structure; it will work just fine. However, you do have to have functions in a function to do commands when someone clicks on a button or something

So what you could do is write classes for these then have methods in the class that handle commands for the button clicks and such.

Here's an example:

import tkinter as tk

class Window1:
    def __init__(self, master):
        pass
        # Create labels, entries,buttons
    def button_click(self):
        pass
        # If button is clicked, run this method and open window 2


class Window2:
    def __init__(self, master):
        #create buttons,entries,etc

    def button_method(self):
        #run this when button click to close window
        self.master.destroy()

def main(): #run mianloop 
    root = tk.Tk()
    app = Window1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Usually tk programs with multiple windows are multiple big classes and in the __init__ all the entries, labels etc are created and then each method is to handle button click events

There isn't really a right way to do it, whatever works for you and gets the job done as long as its readable and you can easily explain it because if you cant easily explain your program, there probably is a better way to do it.

Take a look at Thinking in Tkinter.

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

This is the way I solved my problem:

  1. Right click the folder that has uncommitted changes on your local
  2. Click Team > Advanced > Assume Unchanged
  3. Pull from master.

UPDATE:

As Hugo Zuleta rightly pointed out, you should be careful while applying this. He says that it might end up saying the branch is up to date, but the changes aren't shown, resulting in desync from the branch.

SQL select max(date) and corresponding value

Each MAX function is evaluated individually. So MAX(CompletedDate) will return the value of the latest CompletedDate column and MAX(Notes) will return the maximum (i.e. alphabeticaly highest) value.

You need to structure your query differently to get what you want. This question had actually already been asked and answered several times, so I won't repeat it:

How to find the record in a table that contains the maximum value?

Finding the record with maximum value in SQL

Oracle: how to add minutes to a timestamp?

In addition to being able to add a number of days to a date, you can use interval data types assuming you are on Oracle 9i or later, which can be somewhat easier to read,

SQL> ed
Wrote file afiedt.buf
SELECT sysdate, sysdate + interval '30' minute FROM dual
SQL> /

SYSDATE              SYSDATE+INTERVAL'30'
-------------------- --------------------
02-NOV-2008 16:21:40 02-NOV-2008 16:51:40

"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)

I was missing a dependency somewhere else along the line, so I installed the other requirements for the project like this:

pip install --user -r requirements.txt

Pandas read_csv from url

url = "https://github.com/cs109/2014_data/blob/master/countries.csv"
c = pd.read_csv(url, sep = "\t")

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
    ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;

Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.

How to pass in password to pg_dump?

You just need to open pg_hba.conf and sets trust in all methods. That's works for me. Therefore the security is null.

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

Null must not be set to string...

$this->db->where('archived IS NOT', null);

It works properly when null is not wrapped into quotes.

What happens to a declared, uninitialized variable in C? Does it have a value?

Static variables (file scope and function static) are initialized to zero:

int x; // zero
int y = 0; // also zero

void foo() {
    static int x; // also zero
}

Non-static variables (local variables) are indeterminate. Reading them prior to assigning a value results in undefined behavior.

void foo() {
    int x;
    printf("%d", x); // the compiler is free to crash here
}

In practice, they tend to just have some nonsensical value in there initially - some compilers may even put in specific, fixed values to make it obvious when looking in a debugger - but strictly speaking, the compiler is free to do anything from crashing to summoning demons through your nasal passages.

As for why it's undefined behavior instead of simply "undefined/arbitrary value", there are a number of CPU architectures that have additional flag bits in their representation for various types. A modern example would be the Itanium, which has a "Not a Thing" bit in its registers; of course, the C standard drafters were considering some older architectures.

Attempting to work with a value with these flag bits set can result in a CPU exception in an operation that really shouldn't fail (eg, integer addition, or assigning to another variable). And if you go and leave a variable uninitialized, the compiler might pick up some random garbage with these flag bits set - meaning touching that uninitialized variable may be deadly.

How can strip whitespaces in PHP's variable?

You can use trim function from php to trim both sides (left and right)

 trim($yourinputdata," ");

Or

trim($yourinputdata);

You can also use

ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a string

System: PHP 4,5,7
Docs: http://php.net/manual/en/function.trim.php

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

Sample database for exercise

This is an online database but you can try with the stackoverflow database: https://data.stackexchange.com/stackoverflow/query/new

You also can download its dumps here:

https://archive.org/download/stackexchange

Find and extract a number from a string

You can do this using String property like below:

 return new String(input.Where(Char.IsDigit).ToArray()); 

which gives only number from string.

Java generics - why is "extends T" allowed but not "implements T"?

In fact, when using generic on interface, the keyword is also extends. Here is the code example:

There are 2 classes that implements the Greeting interface:

interface Greeting {
    void sayHello();
}

class Dog implements Greeting {
    @Override
    public void sayHello() {
        System.out.println("Greeting from Dog: Hello ");
    }
}

class Cat implements Greeting {
    @Override
    public void sayHello() {
        System.out.println("Greeting from Cat: Hello ");
    }
}

And the test code:

@Test
public void testGeneric() {
    Collection<? extends Greeting> animals;

    List<Dog> dogs = Arrays.asList(new Dog(), new Dog(), new Dog());
    List<Cat> cats = Arrays.asList(new Cat(), new Cat(), new Cat());

    animals = dogs;
    for(Greeting g: animals) g.sayHello();

    animals = cats;
    for(Greeting g: animals) g.sayHello();
}

How to print variables without spaces between values

To build off what Martjin was saying. I'd use string interpolation/formatting.

In Python 2.x which seems to be what you're using due to the lack of parenthesis around the print function you do:

print 'Value is "%d"' % value

In Python 3.x you'd use the format method instead, so you're code would look like this.

message = 'Value is "{}"'
print(message.format(value))

When use getOne and findOne methods Spring Data JPA

The basic difference is that getOne is lazy loaded and findOne is not.

Consider the following example:

public static String NON_EXISTING_ID = -1;
...
MyEntity getEnt = myEntityRepository.getOne(NON_EXISTING_ID);
MyEntity findEnt = myEntityRepository.findOne(NON_EXISTING_ID);

if(findEnt != null) {
     findEnt.getText(); // findEnt is null - this code is not executed
}

if(getEnt != null) {
     getEnt.getText(); // Throws exception - no data found, BUT getEnt is not null!!!
}

mysql: SOURCE error 2?

May be the file name or path you are used may be incorrect

In my system i created file abcd.sql at c:\

and used command mysql> source c:\abcd.sql Then i got result

Why doesn't Java support unsigned ints?

With JDK8 it does have some support for them.

We may yet see full support of unsigned types in Java despite Gosling's concerns.

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

Sort an array of objects in React and render them

Try lodash sortBy

import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
    console.log("application")
    )
)

Read more : lodash.sortBy

How can I apply styles to multiple classes at once?

If you use as following, your code can be more effective than you wrote. You should add another feature.

.abc, .xyz {
margin-left:20px;
width: 100px;
height: 100px;
} 

OR

a.abc, a.xyz {
margin-left:20px;
width: 100px;
height: 100px;
} 

OR

a {
margin-left:20px;
width: 100px;
height: 100px;
} 

How to read a file into vector in C++?

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
fstream dataFile;
string name , word , new_word;
vector<string> test;
char fileName[80];
cout<<"Please enter the file name : ";
cin >> fileName;
dataFile.open(fileName);
if(dataFile.fail())
{
     cout<<"File can not open.\n";
     return 0;
}
cout<<"File opened.\n";
cout<<"Please enter the word : ";
cin>>word;
cout<<"Please enter the new word : ";
cin >> new_word;
while (!dataFile.fail() && !dataFile.eof())
{
      dataFile >> name;
      test.push_back(name);
}
dataFile.close();

}

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to split a delimited string into an array in awk?

Have you tried:

echo "12|23|11" | awk '{split($0,a,"|"); print a[3],a[2],a[1]}'

How to establish ssh key pair when "Host key verification failed"

Step1:$Bhargava.ssh#

ssh-keygen -R 199.95.30.220

step2:$Bhargava.ssh #

ssh-copy-id [email protected]

          Enter the the password.........

step3: Bhargava .ssh #

ssh [email protected]

Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-68-generic x86_64) * Documentation: https://help.ubuntu.com/ Ubuntu 14.04.3 LTS server : 228839 ip : 199.95.30.220 hostname : qt.example.com System information as of Thu Mar 24 02:13:43 EDT 2016 System load: 0.67 Processes: 321 Usage of /home: 5.1% of 497.80GB Users logged in: 0 Memory usage: 53% IP address for eth0: 199.95.30.220 Swap usage: 16% IP address for docker0: 172.17.0.1 Graph this data and manage this system at: https://landscape.canonical.com/ Last login: Wed Mar 23 02:07:29 2016 from 103.200.41.50

hostname@qt:~$

how to set default main class in java?

In Netbeans 11(Gladle Project) follow these steps:

In the tab files>yourprojectname> double click in the file "build.gladle" than set in line "mainClassName:'yourpackagepath.YourMainClass'"

Hope this helps!

Is it possible to assign numeric value to an enum in Java?

public enum EXIT_CODE {
    A(104), B(203);

    private int numVal;

    EXIT_CODE(int numVal) {
        this.numVal = numVal;
    }

    public int getNumVal() {
        return numVal;
    }
}

How to remove last n characters from every element in the R vector

Here's a way with gsub:

cs <- c("foo_bar","bar_foo","apple","beer")
gsub('.{3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"

Have nginx access_log and error_log log to STDOUT and STDERR of master process

For a debug purpose:

/usr/sbin/nginx -g "daemon off;error_log /dev/stdout debug;"

For a classic purpose

/usr/sbin/nginx -g "daemon off;error_log /dev/stdout info;"

Require

Under the server bracket on the config file

access_log /dev/stdout;

how to set background image in submit button?

.button {
    border: none;
    background: url('/forms/up.png') no-repeat top left;
    padding: 2px 8px;
}

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Rolling back local and remote git repository by 1 commit

Here's an updated version of the procedure which is safer.

git reset --hard HEAD^ 
git push --force-with-lease

git push -f will indiscriminately replace the remote repository with your own changes. If someone else has pushed changes they will be lost. git push --force-with-lease will only push your rebase if the repository is as you expect. If someone else has already pushed your push will fail.

See –force considered harmful; understanding git’s –force-with-lease.

I recommend aliasing this as repush = push --force-with-lease.

What if somebody has already pulled the repo? What would I do then?

Tell them to git pull --rebase=merges. Instead of a git fetch origin and git merge origin/master it will git fetch origin and git rebase -r origin/master. This will rewrite any of their local changes to master on top of the new rebased origin/master. -r will preserve any merges they may have made.

I recommend making this the default behavior for pulling. It is safe, will handle other's rebasing, and results in less unnecessary merges.

[pull]
        rebase = merges

How to show imageView full screen on imageView click?

Use Immersive Full-Screen Mode

enter image description here

call fullScreen() on ImageView click.

 public void fullScreen() {

        // BEGIN_INCLUDE (get_current_ui_flags)
        // The UI options currently enabled are represented by a bitfield.
        // getSystemUiVisibility() gives us that bitfield.
        int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
        int newUiOptions = uiOptions;
        // END_INCLUDE (get_current_ui_flags)
        // BEGIN_INCLUDE (toggle_ui_flags)
        boolean isImmersiveModeEnabled =
                ((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
        if (isImmersiveModeEnabled) {
            Log.i(TAG, "Turning immersive mode mode off. ");
        } else {
            Log.i(TAG, "Turning immersive mode mode on.");
        }

        // Navigation bar hiding:  Backwards compatible to ICS.
        if (Build.VERSION.SDK_INT >= 14) {
            newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        }

        // Status bar hiding: Backwards compatible to Jellybean
        if (Build.VERSION.SDK_INT >= 16) {
            newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
        }

        // Immersive mode: Backward compatible to KitKat.
        // Note that this flag doesn't do anything by itself, it only augments the behavior
        // of HIDE_NAVIGATION and FLAG_FULLSCREEN.  For the purposes of this sample
        // all three flags are being toggled together.
        // Note that there are two immersive mode UI flags, one of which is referred to as "sticky".
        // Sticky immersive mode differs in that it makes the navigation and status bars
        // semi-transparent, and the UI flag does not get cleared when the user interacts with
        // the screen.
        if (Build.VERSION.SDK_INT >= 18) {
            newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        }

        getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
        //END_INCLUDE (set_ui_flags)
    }

Read more

Example Download

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

Printing image with PrintDocument. how to adjust the image to fit paper size

You can use my code here

//Print Button Event Handeler
private void btnPrint_Click(object sender, EventArgs e)
{
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += PrintPage;
    //here to select the printer attached to user PC
    PrintDialog printDialog1 = new PrintDialog();
    printDialog1.Document = pd;
    DialogResult result = printDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        pd.Print();//this will trigger the Print Event handeler PrintPage
    }
}

//The Print Event handeler
private void PrintPage(object o, PrintPageEventArgs e)
{
    try
    {
        if (File.Exists(this.ImagePath))
        {
            //Load the image from the file
            System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");

            //Adjust the size of the image to the page to print the full image without loosing any part of it
            Rectangle m = e.MarginBounds;

            if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
            {
                m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
            }
            else
            {
                m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
            }
            e.Graphics.DrawImage(img, m);
        }
    }
    catch (Exception)
    {

    }
}

What's the difference between passing by reference vs. passing by value?

Pass by value sends a COPY of the data stored in the variable you specify, pass by reference sends a direct link to the variable itself. So if you pass a variable by reference and then change the variable inside the block you passed it into, the original variable will be changed. If you simply pass by value, the original variable will not be able to be changed by the block you passed it into but you will get a copy of whatever it contained at the time of the call.

Specify multiple attribute selectors in CSS

[class*="test"],[class="second"] {
background: #ffff00;
}

How to make UIButton's text alignment center? Using IB

Try Like this :

yourButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
yourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

Simplest way to set image as JPanel background

class Logo extends JPanel
{
    Logo()
    {
        //code
    }
    @Override
    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        ImageIcon img = new ImageIcon("logo.jpg");
        g.drawImage(img.getImage(), 0, 0, this.getWidth(), this.getHeight(), null);
    }
}

How to move up a directory with Terminal in OS X

cd .. will back the directory up by one. If you want to reach a folder in the parent directory, you can do something like cd ../foldername. You can use the ".." trick as many times as you want to back up through multiple parent directories. For example, cd ../../Applications would take you to Macintosh HD/Applications

MySQL error: key specification without a key length

The error happens because MySQL can index only the first N chars of a BLOB or TEXT column. So The error mainly happens when there is a field/column type of TEXT or BLOB or those belong to TEXT or BLOB types such as TINYBLOB, MEDIUMBLOB, LONGBLOB, TINYTEXT, MEDIUMTEXT, and LONGTEXT that you try to make a primary key or index. With full BLOB or TEXT without the length value, MySQL is unable to guarantee the uniqueness of the column as it’s of variable and dynamic size. So, when using BLOB or TEXT types as an index, the value of N must be supplied so that MySQL can determine the key length. However, MySQL doesn’t support a key length limit on TEXT or BLOB. TEXT(88) simply won’t work.

The error will also pop up when you try to convert a table column from non-TEXT and non-BLOB type such as VARCHAR and ENUM into TEXT or BLOB type, with the column already been defined as unique constraints or index. The Alter Table SQL command will fail.

The solution to the problem is to remove the TEXT or BLOB column from the index or unique constraint or set another field as primary key. If you can't do that, and wanting to place a limit on the TEXT or BLOB column, try to use VARCHAR type and place a limit of length on it. By default, VARCHAR is limited to a maximum of 255 characters and its limit must be specified implicitly within a bracket right after its declaration, i.e VARCHAR(200) will limit it to 200 characters long only.

Sometimes, even though you don’t use TEXT or BLOB related type in your table, the Error 1170 may also appear. It happens in a situation such as when you specify VARCHAR column as primary key, but wrongly set its length or characters size. VARCHAR can only accepts up to 256 characters, so anything such as VARCHAR(512) will force MySQL to auto-convert the VARCHAR(512) to a SMALLTEXT datatype, which subsequently fails with error 1170 on key length if the column is used as primary key or unique or non-unique index. To solve this problem, specify a figure less than 256 as the size for VARCHAR field.

Reference: MySQL Error 1170 (42000): BLOB/TEXT Column Used in Key Specification Without a Key Length

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

Getting the object's property name

Other than "Object.keys( obj )", we have very simple "for...in" loop - which loops over enumerable property names of an object.

_x000D_
_x000D_
const obj = {"fName":"John","lName":"Doe"};_x000D_
_x000D_
for (const key in obj) {_x000D_
    //This will give key_x000D_
      console.log(key);_x000D_
    //This will give value_x000D_
    console.log(obj[key]);_x000D_
    _x000D_
}
_x000D_
_x000D_
_x000D_

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

How to urlencode a querystring in Python?

If the urllib.parse.urlencode( ) is giving you errors , then Try the urllib3 module .

The syntax is as follows :

import urllib3
urllib3.request.urlencode({"user" : "john" }) 

How to draw border on just one side of a linear layout?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#f28b24" />
            <stroke
                android:width="1dp"
                android:color="#f28b24" />
            <corners
                android:radius="0dp"/>
            <padding
                android:left="0dp"
                android:top="0dp"
                android:right="0dp"
                android:bottom="0dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#f28b24"
                android:endColor="#f28b24"
                android:angle="270" />
            <stroke
                android:width="0dp"
                android:color="#f28b24" />
            <corners
                android:bottomLeftRadius="8dp"
                android:bottomRightRadius="0dp"
                android:topLeftRadius="0dp"
                android:topRightRadius="0dp"/>
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

How can I make the Android emulator show the soft keyboard?

Settings > Language & input > Current keyboard > Hardware Switch ON.

This option worked.

Minimum and maximum date

As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.

new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1

initialize a const array in a class initializer in C++

A solution without using the heap with std::vector is to use boost::array, though you can't initialize array members directly in the constructor.

#include <boost/array.hpp>

const boost::array<int, 2> aa={ { 2, 3} };

class A {
    const boost::array<int, 2> b;
    A():b(aa){};
};

Replace Multiple String Elements in C#

Quicker - no. More effective - yes, if you will use the StringBuilder class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.

If you expect this method to be actively called on multiple Strings of significant length, it might be better to "migrate" its implementation onto the StringBuilder class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.

public static class StringExtention
{
    public static string clean(this string s)
    {
        StringBuilder sb = new StringBuilder (s);

        sb.Replace("&", "and");
        sb.Replace(",", "");
        sb.Replace("  ", " ");
        sb.Replace(" ", "-");
        sb.Replace("'", "");
        sb.Replace(".", "");
        sb.Replace("eacute;", "é");

        return sb.ToString().ToLower();
    }
}

How can I see the size of files and directories in linux?

du -sh [file_name]

works perfectly to get size of a particular file.

how to write an array to a file Java

Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:

public static void write (String filename, int[]x) throws IOException{
  BufferedWriter outputWriter = null;
  outputWriter = new BufferedWriter(new FileWriter(filename));
  for (int i = 0; i < x.length; i++) {
    // Maybe:
    outputWriter.write(x[i]+"");
    // Or:
    outputWriter.write(Integer.toString(x[i]);
    outputWriter.newLine();
  }
  outputWriter.flush();  
  outputWriter.close();  
}

If you just want to print out the array like [1, 2, 3, ....], you can replace the loop with this one liner:

outputWriter.write(Arrays.toString(x));

How to check if bootstrap modal is open, so I can use jquery validate?

You can also directly use jQuery.

$('#myModal').is(':visible');

What is difference between Lightsail and EC2?

Testing¹ reveals that Lightsail instances in fact are EC2 instances, from the t2 class of burstable instances.

EC2, of course, has many more instance families and classes other than the t2, almost all of which are more "powerful" (or better equipped for certain tasks) than these, but also much more expensive. But for meaningful comparisons, the 512 MiB Lightsail instance appears to be completely equivalent in specifications to the similarly-priced t2.nano, the 1GiB is a t2.micro, the 2 GiB is a t2.small, etc.

Lightsail is a lightweight, simplified product offering -- hard disks are fixed size EBS SSD volumes, instances are still billable when stopped, security group rules are much less flexible, and only a very limited subset of EC2 features and options are accessible.

It also has a dramatically simplified console, and even though the machines run in EC2, you can't see them in the EC2 section of the AWS console. The instances run in a special VPC, but this aspect is also provisioned automatically, and invisible in the console. Lightsail supports optionally peering this hidden VPC with your default VPC in the same AWS region, allowing Lightsail instances to access services like EC2 and RDS in the default VPC within the same AWS account.²

Bandwidth is unlimited, but of course free bandwidth is not -- however, Lightsail instances do include a significant monthly bandwidth allowance before any bandwidth-related charges apply.³ Lightsail also has a simplified interface to Route 53 with limited functionality.

But if those sound like drawbacks, they aren't. The point of Lightsail seems to be simplicity. The flexibility of EC2 (and much of AWS) leads inevitably to complexity. The target market for Lightsail appears to be those who "just want a simple VPS" without having to navigate the myriad options available in AWS services like EC2, EBS, VPC, and Route 53. There is virtually no learning curve, here. You don't even technically need to know how to use SSH with a private key -- the Lightsail console even has a built-in SSH client -- but there is no requirement that you use it. You can access these instances normally, with a standard SSH client.


¹Lightsail instances, just like "regular" EC2 (VPC and Classic) instances, have access to the instance metadata service, which allows an instance to discover things about itself, such as its instance type and availability zone. Lightsail instances are identified in the instance metadata as t2 machines.

²The Lightsail docs are not explicit about the fact that peering only works with your Default VPC, but this appears to be the case. If your AWS account was created in 2013 or before, then you may not actually have a VPC with the "Default VPC" designation. This can be resolved by submitting a support request, as I explained in Can't establish VPC peering connection from Amazon Lightsail (at Server Fault).

³The bandwidth allowance applies to both inbound and outbound traffic; after this total amount of traffic is exceeded, inbound traffic continues to be free, but outbound traffic becomes billable. See "What does data transfer cost?" in the Lightsail FAQ.

Get the value in an input text box

//Get
var bla = $('#txt_name').val();

//Set
$('#txt_name').val(bla);

C++ compiling on Windows and Linux: ifdef switch

It depends on the compiler. If you compile with, say, G++ on Linux and VC++ on Windows, this will do :

#ifdef linux
    ...
#elif _WIN32
    ...
#else
    ...
#endif

How to make for loops in Java increase by increments other than 1

It should be like this

for(int j = 0; j<=90; j += 3) 

but watch out for

for(int j = 0; j<=90; j =+ 3) 

or

for(int j = 0; j<=90; j = j + 3)

How to tell if a string is not defined in a Bash shell script

call set without any arguments.. it outputs all the vars defined..
the last ones on the list would be the ones defined in your script..
so you could pipe its output to something that could figure out what things are defined and whats not

Best place to insert the Google Analytics code

Google used to recommend putting it just before the </body> tag, because the original method they provided for loading ga.js was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the </head> tag.

<head> will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.

As a matter of personal preference, I like to include it in the <head>, but its really a matter of preference.

Sorting dropdown alphabetically in AngularJS

Angular has an orderBy filter that can be used like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name'"></select>

See this fiddle for an example.

It's worth noting that if track by is being used it needs to appear after the orderBy filter, like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name' track by f.id"></select>

CSS: Fix row height

You can also try this, if this is what you need:

<style type="text/css">
   ....
   table td div {height:20px;overflow-y:hidden;}
   table td.col1 div {width:100px;}
   table td.col2 div {width:300px;}
</style>


<table>
<tbody>
    <tr><td class="col1"><div>test</div></td></tr>
    <tr><td class="col2"><div>test</div></td></tr>
</tbody>
</table>

javascript: detect scroll end

The accepted answer was fundamentally flawed, it has since been deleted. The correct answer is:

function scrolled(e) {
  if (myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight) {
    scrolledToBottom(e);
  }
}

Tested this in Firefox, Chrome and Opera. It works.

Selenium and xpath: finding a div with a class/id and verifying text inside

To account for leading and trailing whitespace, you probably want to use normalize-space()

//div[contains(@class, 'Caption') and normalize-space(.)='Model saved']

and

//div[@id='alertLabel' and normalize-space(.)='Save to server successful']

Note that //div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved'] also works.

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

How do I replace a character at a particular index in JavaScript?

In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.

You'll need to define the replaceAt() function yourself:

String.prototype.replaceAt = function(index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

And use it like this:

var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // Should display He!!o World

How to get root view controller?

Swift 3

let rootViewController = UIApplication.shared.keyWindow?.rootViewController

`getchar()` gives the same output as the input string

In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.

How to get exit code when using Python subprocess communicate method?

You should first make sure that the process has completed running and the return code has been read out using the .wait method. This will return the code. If you want access to it later, it's stored as .returncode in the Popen object.

Dynamic type languages versus static type languages

Perhaps the single biggest "benefit" of dynamic typing is the shallower learning curve. There is no type system to learn and no non-trivial syntax for corner cases such as type constraints. That makes dynamic typing accessible to a lot more people and feasible for many people for whom sophisticated static type systems are out of reach. Consequently, dynamic typing has caught on in the contexts of education (e.g. Scheme/Python at MIT) and domain-specific languages for non-programmers (e.g. Mathematica). Dynamic languages have also caught on in niches where they have little or no competition (e.g. Javascript).

The most concise dynamically-typed languages (e.g. Perl, APL, J, K, Mathematica) are domain specific and can be significantly more concise than the most concise general-purpose statically-typed languages (e.g. OCaml) in the niches they were designed for.

The main disadvantages of dynamic typing are:

  • Run-time type errors.

  • Can be very difficult or even practically impossible to achieve the same level of correctness and requires vastly more testing.

  • No compiler-verified documentation.

  • Poor performance (usually at run-time but sometimes at compile time instead, e.g. Stalin Scheme) and unpredictable performance due to dependence upon sophisticated optimizations.

Personally, I grew up on dynamic languages but wouldn't touch them with a 40' pole as a professional unless there were no other viable options.

How to get different colored lines for different plots in a single figure?

Matplotlib does this by default.

E.g.:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()

Basic plot demonstrating color cycling

And, as you may already know, you can easily add a legend:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Basic plot with legend

If you want to control the colors that will be cycled through:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Plot showing control over default color cycling

If you're unfamiliar with matplotlib, the tutorial is a good place to start.

Edit:

First off, if you have a lot (>5) of things you want to plot on one figure, either:

  1. Put them on different plots (consider using a few subplots on one figure), or
  2. Use something other than color (i.e. marker styles or line thickness) to distinguish between them.

Otherwise, you're going to wind up with a very messy plot! Be nice to who ever is going to read whatever you're doing and don't try to cram 15 different things onto one figure!!

Beyond that, many people are colorblind to varying degrees, and distinguishing between numerous subtly different colors is difficult for more people than you may realize.

That having been said, if you really want to put 20 lines on one axis with 20 relatively distinct colors, here's one way to do it:

import matplotlib.pyplot as plt
import numpy as np

num_plots = 20

# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))

# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
    plt.plot(x, i * x + 5 * i)
    labels.append(r'$y = %ix + %i$' % (i, 5*i))

# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center', 
           bbox_to_anchor=[0.5, 1.1], 
           columnspacing=1.0, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)

plt.show()

Unique colors for 20 lines based on a given colormap

How to get the height of a body element

We were trying to avoid using the IE specific

$window[0].document.body.clientHeight 

And found that the following jQuery will not consistently yield the same value but eventually does at some point in our page load scenario which worked for us and maintained cross-browser support:

$(document).height()

getting the table row values with jquery

Try this:

jQuery('.delbtn').on('click', function() {
    var $row = jQuery(this).closest('tr');
    var $columns = $row.find('td');

    $columns.addClass('row-highlight');
    var values = "";

    jQuery.each($columns, function(i, item) {
        values = values + 'td' + (i + 1) + ':' + item.innerHTML + '<br/>';
        alert(values);
    });
    console.log(values);
});

DEMO

Truncate a SQLite table if it exists?

"sqllite" dosn't have "TRUNCATE " order like than mysql, then we have to get other way... this function (reset_table) frist delete all data in table and then reset AUTOINCREMENT key in table.... now you can use this function every where you want...

example :

private SQLiteDatabase mydb;
private final String dbPath = "data/data/your_project_name/databases/";
private final String dbName = "your_db_name";


public void reset_table(String table_name){
    open_db();

    mydb.execSQL("Delete from "+table_name);
    mydb.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE name='"+table_name+"';");

    close_db();
}

public void open_db(){

    mydb = SQLiteDatabase.openDatabase(dbPath + dbName + ".db", null, SQLiteDatabase.OPEN_READWRITE);
}
public void close_db(){

    mydb.close();
}

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

Try to run gradle at the command line first. It might prompt you to setup and environment variable:

export _JAVA_OPTIONS="-Xms256m -Xmx1024m"

Read more here: 1, 2


Further make sure that the Android SDK build tools (adb, aapt, dx, dx.jar) are available in the PATH. If not you can create symlinks at the appropriate locations. They changed with the release of new SDK versions. Here is a shell script which creates the symlinks within the $ANDROID_HOME folder for you.

What is the purpose of Order By 1 in SQL select statement?

This will sort your results by the first column returned. In the example it will sort by payment_date.

How to get Locale from its String representation in Java?

You can use this on Android. Works fine for me.

private static final Pattern localeMatcher = Pattern.compile
        ("^([^_]*)(_([^_]*)(_#(.*))?)?$");

public static Locale parseLocale(String value) {
    Matcher matcher = localeMatcher.matcher(value.replace('-', '_'));
    return matcher.find()
            ? TextUtils.isEmpty(matcher.group(5))
                ? TextUtils.isEmpty(matcher.group(3))
                    ? TextUtils.isEmpty(matcher.group(1))
                        ? null
                        : new Locale(matcher.group(1))
                    : new Locale(matcher.group(1), matcher.group(3))
                : new Locale(matcher.group(1), matcher.group(3),
                             matcher.group(5))
            : null;
}

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

This will validate against special characters and leading and trailing spaces:

var strString = "Your String";

strString.match(/^[A-Za-z0-9][A-Za-z0-9 ]\*[A-Za-z0-9]\*$/)

Add column with constant value to pandas dataframe

With modern pandas you can just do:

df['new'] = 0

Calculating the distance between 2 points

the algorithm : ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) < 25

Django CSRF check failing with an Ajax POST request

The issue is because django is expecting the value from the cookie to be passed back as part of the form data. The code from the previous answer is getting javascript to hunt out the cookie value and put it into the form data. Thats a lovely way of doing it from a technical point of view, but it does look a bit verbose.

In the past, I have done it more simply by getting the javascript to put the token value into the post data.

If you use {% csrf_token %} in your template, you will get a hidden form field emitted that carries the value. But, if you use {{ csrf_token }} you will just get the bare value of the token, so you can use this in javascript like this....

csrf_token = "{{ csrf_token }}";

Then you can include that, with the required key name in the hash you then submit as the data to the ajax call.

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

Android Camera : data intent returns null

I´ve had experienced this problem, the intent is not null but the information sent via this intent is not received in onActionActivit()

enter image description here

This is a better solution using getContentResolver() :

    private Uri imageUri;
    private ImageView myImageView;
    private Bitmap thumbnail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

      ...
      ...    
      ...
      myImageview = (ImageView) findViewById(R.id.pic); 

      values = new ContentValues();
      values.put(MediaStore.Images.Media.TITLE, "MyPicture");
      values.put(MediaStore.Images.Media.DESCRIPTION, "Photo taken on " + System.currentTimeMillis());
      imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
      startActivityForResult(intent, PICTURE_RESULT);

  }

the onActivityResult() get a bitmap stored by getContentResolver() :

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {

            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                myImageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

introducir la descripción de la imagen aquí introducir la descripción de la imagen aquí

Check my example in github:

https://github.com/Jorgesys/TakePicture

Does a valid XML file require an XML declaration?

Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.

More elegant way of declaring multiple variables at the same time

a, b, c, d, e, g, h, i, j = (True,)*9
f = False

What is the best way to compare 2 folder trees on windows?

Beyond compare allows you to do that and much more.

It's one of those tools I can't live without.
Take a look here for a reference on the scripting options

What's a good way to extend Error in JavaScript?

As some people have said, it's fairly easy with ES6:

class CustomError extends Error { }

So I tried that within my app, (Angular, Typescript) and it just didn't work. After some time I've found that the problem is coming from Typescript :O

See https://github.com/Microsoft/TypeScript/issues/13965

It's very disturbing because if you do:

class CustomError extends Error {}
?

try {
  throw new CustomError()
} catch(e) {
  if (e instanceof CustomError) {
    console.log('Custom error');
  } else {
    console.log('Basic error');
  }
}

In node or directly into your browser it'll display: Custom error

Try to run that with Typescript in your project on on Typescript playground, it'll display Basic error...

The solution is to do the following:

class CustomError extends Error {
  // we have to do the following because of: https://github.com/Microsoft/TypeScript/issues/13965
  // otherwise we cannot use instanceof later to catch a given type
  public __proto__: Error;

  constructor(message?: string) {
    const trueProto = new.target.prototype;
    super(message);

    this.__proto__ = trueProto;
  }
}

Strip / trim all strings of a dataframe

def trim(x):
    if x.dtype == object:
        x = x.str.split(' ').str[0]
    return(x)

df = df.apply(trim)

Cannot serve WCF services in IIS on Windows 8

For Windows Server 2012, the solution is very similar to faester's (see above). From the Server Manager, click on Add roles and features, select the appropriate server, then select Features. Under .NET Framework 4.5 Features, you'll see WCF Services, and under that, you'll find HTTP Activation.

Convert Java Array to Iterable

While a similar answer has already been sort of posted, I think the reason to use the new PrimitiveIterator.OfInt was not clear. A good solution is to use Java 8 PrimitiveIterator since it's specialized for primitive int types (and avoids the extra boxing/unboxing penalty):

    int[] arr = {1,2,3};
    // If you use Iterator<Integer> here as type then you can't get the actual benefit of being able to use nextInt() later
    PrimitiveIterator.OfInt iterator = Arrays.stream(arr).iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.nextInt());
        // Use nextInt() instead of next() here to avoid extra boxing penalty
    }

Ref: https://doc.bccnsoft.com/docs/jdk8u12-docs/api/java/util/PrimitiveIterator.OfInt.html

What are these attributes: `aria-labelledby` and `aria-hidden`

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-hidden:

aria-hidden attribute is used to hide content for visually impaired users who navigate through application using screen readers (JAWS, NVDA,...).

aria-hidden attribute is used with values true, false.

How To Use:

<i class = "fa fa-books" aria-hidden = "true"></i>

using aria-hidden = "true" on the <i> hides content to screen reader users with no visual change in the application.

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type = "edit" aria-label = "search" placeholder = "search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id = "sd"> Search </span>

<input type = "text" aria-labelledby = "sd">

aria-labelledby can also be used to combine two labels for screen reader users

Approach 2:

<span id = "de"> Billing Address </span>

<span id = "sd"> First Name </span>

<input type = "text" aria-labelledby = "de sd">

Center button under form in bootstrap

Try giving

default width, display it with block and center it with margin: 0 auto;

like this:

<p style="display:block; line-height: 70px; width:200px; margin:0 auto;"><button type="submit" class="btn">Confirm</button></p>

Why do we use volatile keyword?

Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.


Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

Best way to remove an event handler in jQuery?

if you set the onclick via html you need to removeAttr ($(this).removeAttr('onclick'))

if you set it via jquery (as the after the first click in my examples above) then you need to unbind($(this).unbind('click'))

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

You need to annotate your Customer class with @Named or @Model annotation:

package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
    private String email;
    private String password;
}

or create/modify beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
</beans>

What is a blob URL and why it is used?

Blob URLs (ref W3C, official name) or Object-URLs (ref. MDN and method name) are used with a Blob or a File object.

src="blob:https://crap.crap" I opened the blob url that was in src of video it gave a error and i can't open but was working with the src tag how it is possible?

Blob URLs can only be generated internally by the browser. URL.createObjectURL() will create a special reference to the Blob or File object which later can be released using URL.revokeObjectURL(). These URLs can only be used locally in the single instance of the browser and in the same session (ie. the life of the page/document).

What is blob url?
Why it is used?

Blob URL/Object URL is a pseudo protocol to allow Blob and File objects to be used as URL source for things like images, download links for binary data and so forth.

For example, you can not hand an Image object raw byte-data as it would not know what to do with it. It requires for example images (which are binary data) to be loaded via URLs. This applies to anything that require an URL as source. Instead of uploading the binary data, then serve it back via an URL it is better to use an extra local step to be able to access the data directly without going via a server.

It is also a better alternative to Data-URI which are strings encoded as Base-64. The problem with Data-URI is that each char takes two bytes in JavaScript. On top of that a 33% is added due to the Base-64 encoding. Blobs are pure binary byte-arrays which does not have any significant overhead as Data-URI does, which makes them faster and smaller to handle.

Can i make my own blob url on a server?

No, Blob URLs/Object URLs can only be made internally in the browser. You can make Blobs and get File object via the File Reader API, although BLOB just means Binary Large OBject and is stored as byte-arrays. A client can request the data to be sent as either ArrayBuffer or as a Blob. The server should send the data as pure binary data. Databases often uses Blob to describe binary objects as well, and in essence we are talking basically about byte-arrays.

if you have then Additional detail

You need to encapsulate the binary data as a BLOB object, then use URL.createObjectURL() to generate a local URL for it:

var blob = new Blob([arrayBufferWithPNG], {type: "image/png"}),
    url = URL.createObjectURL(blob),
    img = new Image();

img.onload = function() {
    URL.revokeObjectURL(this.src);     // clean-up memory
    document.body.appendChild(this);   // add image to DOM
}

img.src = url;                         // can now "stream" the bytes

Note that URL may be prefixed in webkit-browsers, so use:

var url = (URL || webkitURL).createObjectURL(...);

"A lambda expression with a statement body cannot be converted to an expression tree"

For your specific case, the body is for creating a variable, and switching to IEnumerable will force all the operations to be processed on client-side, I propose the following solution.

Obj[] myArray = objects
.Select(o => new
{
    SomeLocalVar = o.someVar, // You can even use any LINQ statement here
    Info = o,
}).Select(o => new Obj()
{
    Var1 = o.SomeLocalVar,
    Var2 = o.Info.var2,
    Var3 = o.SomeLocalVar.SubValue1,
    Var4 = o.SomeLocalVar.SubValue2,
}).ToArray();

Edit: Rename for C# Coding Convention

How do I fix a Git detached head?

Here's what I just did after I realized I was on a detached head and had already made some changes.

I committed the changes.

$ git commit -m "..."
[detached HEAD 1fe56ad] ...

I remembered the hash (1fe56ad) of the commit. Then I checked out the branch I should have been on.

$ git checkout master
Switched to branch 'master'

Finally I applied the changes of the commit to the branch.

$ git cherry-pick 1fe56ad
[master 0b05f1e] ...

I think this is a bit easier than creating a temporary branch.

MySQL LIKE IN()?

Sorry, there is no operation similar to LIKE IN in mysql.

If you want to use the LIKE operator without a join, you'll have to do it this way:

(field LIKE value OR field LIKE value OR field LIKE value)

You know, MySQL will not optimize that query, FYI.

PHP-FPM and Nginx: 502 Bad Gateway

I made all this similar tweaks, but from time to time I was getting 501/502 errors (daily).

This are my settings on /etc/php5/fpm/pool.d/www.conf to avoid 501 and 502 nginx errors… The server has 16Gb RAM. This configuration is for a 8Gb RAM server so…

sudo nano /etc/php5/fpm/pool.d/www.conf

then set the following values for

pm.max_children = 70
pm.start_servers = 20
pm.min_spare_servers = 20
pm.max_spare_servers = 35
pm.max_requests = 500

After this changes restart php-fpm

sudo service php-fpm restart

Leaflet changing Marker color

In addition to the way @guillermogfer describe, this is the way to do it if you don't want to paste your whole svg code into your react component. You can just place your svg code in a separate file and load it into your code file as a React Component like this:

import { ReactComponent as SatelliteIcon } from "../assets/icons/satellite.svg";

After you do this you can just use your svg as if it is a react component, so like this:

<SatelliteIcon className="svg-icon light-blue" />

What we ended up doing is define some standard svg colors that are used in our application so we can pass them as a class in order to change the color of the svg. If you don't know the color beforehand or don't have a defined set of colors you can dynamically overwrite the properties in your svg file by using the style attribute, something like this:

<SatelliteIcon style={{ stroke: "black" }}/>

In order for this to work it is important that the attributes you are trying to overwrite are set on the element in your svg and not on the individual paths.

In order to get this svg icon to display in leaflet you can use the divIcon as described by @guillermogfer. However, because the html attribute of the divIcon doesn't understand jsx we need to convert it to string first:

L.divIcon({
    className: 'div-icon',
    html: ReactDOMServer.renderToString(
        <SatelliteIcon className="svg-icon light-blue" />
    )
})

Select records from today, this week, this month php mysql

A better solution for "today" is:

SELECT * FROM jokes WHERE DATE(date) = DATE(NOW())

Fastest way to Remove Duplicate Value from a list<> by lambda

You can use this extension method for enumerables containing more complex types:

IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
    var knownKeys = new HashSet<TKey>();
    return source.Where(element => knownKeys.Add(keySelector(element)));
}

How do I remove time part from JavaScript date?

Parse that string into a Date object:

var myDate = new Date('10/11/1955 10:40:50 AM');

Then use the usual methods to get the date's day of month (getDate) / month (getMonth) / year (getFullYear).

var noTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());

Getting current device language in iOS?

Simple Swift 3 function:

@discardableResult
func getLanguageISO() -> String {
    let locale = Locale.current
    guard let languageCode = locale.languageCode,
          let regionCode = locale.regionCode else {
        return "de_DE"
    }
    return languageCode + "_" + regionCode
}

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Is a good idea named the functions with commun alias on the first words for filtre the name with LIKE Example with public schema in Postgresql 9.4, be sure to replace with his scheme

SELECT routine_name 
FROM information_schema.routines 
WHERE routine_type='FUNCTION' 
  AND specific_schema='public'
  AND routine_name LIKE 'aliasmyfunctions%';

How to create a GUID/UUID using iOS

Reviewing the Apple Developer documentation I found the CFUUID object is available on the iPhone OS 2.0 and later.

"Stack overflow in line 0" on Internet Explorer

Also having smartNavigation="true" causes this"

Adding a default value in dropdownlist after binding with database

You can add it programmatically or in the markup, but if you add it programmatically, rather than Add the item, you should Insert it as position zero so that it is the first item:

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");

The default item is expected to be the first item in the list. If you just Add it, it will be on the bottom and will not be selected by default.

How to append multiple values to a list in Python

letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
... 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
    

Find elements inside forms and iframe using Java and Selenium WebDriver

By using https://github.com/nick318/FindElementInFrames You can find webElement across all frames:

SearchByFramesFactory searchFactory = new SearchByFramesFactory(driver);
SearchByFrames searchInFrame = searchFactory.search(() -> driver.findElement(By.tagName("body")));
Optional<WebElement> elem = searchInFrame.getElem();

How to replace text of a cell based on condition in excel

You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM. Then simply type where it says TYPE: what you want to say in QUOTES.

Example.. "OTHER"

Sending and Parsing JSON Objects in Android

you just need to import this

   import org.json.JSONObject;


  constructing the String that you want to send

 JSONObject param=new JSONObject();
 JSONObject post=new JSONObject();

im using two object because you can have an jsonObject within another

post.put("username(here i write the key)","someusername"(here i put the value);
post.put("message","this is a sweet message");
post.put("image","http://localhost/someimage.jpg");
post.put("time":  "present time");

then i put the post json inside another like this

  param.put("post",post);

this is the method that i use to make a request

 makeRequest(param.toString());

public JSONObject makeRequest(String param)
{
    try
    {

setting the connection

        urlConnection = new URL("your url");
        connection = (HttpURLConnection) urlConnection.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
        connection.setReadTimeout(60000);
        connection.setConnectTimeout(60000);
        connection.connect();

setting the outputstream

        dataOutputStream = new DataOutputStream(connection.getOutputStream());

i use this to see in the logcat what i am sending

        Log.d("OUTPUT STREAM  " ,param);
        dataOutputStream.writeBytes(param);
        dataOutputStream.flush();
        dataOutputStream.close();

        InputStream in = new BufferedInputStream(connection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;

here the string is constructed

        while ((line = reader.readLine()) != null)
        {
            result.append(line);
        }

i use this log to see what its comming in the response

         Log.d("INPUTSTREAM: ",result.toString());

instancing a json with the String that contains the server response

        jResponse=new JSONObject(result.toString());

    }
    catch (IOException e) {
        e.printStackTrace();
        return jResponse=null;
    } catch (JSONException e)
    {
        e.printStackTrace();
        return jResponse=null;
    }
    connection.disconnect();
    return jResponse;
}