Programs & Examples On #Smallbasic

Small Basic is a Microsoft product for teaching beginners to program.

How to make program go back to the top of the code instead of closing

write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.

https://wiki.python.org/moin/ForLoop

How to suppress Update Links warning?

Open the VBA Editor of Excel and type this in the Immediate Window (See Screenshot)

Application.AskToUpdateLinks = False 

Close Excel and then open your File. It will not prompt you again. Remember to reset it when you close the workbook else it will not work for other workbooks as well.

ScreenShot:

enter image description here

EDIT

So applying it to your code, your code will look like this

Function getWorkbook(bkPath As String) As Workbook
    Application.AskToUpdateLinks = False
    Set getWorkbook = Workbooks.Open(bkPath, False)
    Application.AskToUpdateLinks = True
End Function

FOLLOWUP

Sigil, The code below works on files with broken links as well. Here is my test code.

Test Conditions

  1. Create 2 new files. Name them Sample1.xlsx and Sample2.xlsx and save them on C:\
  2. In cell A1 of Sample1.xlsx, type this formula ='C:\[Sample2.xlsx]Sheet1'!$A$1
  3. Save and close both the files
  4. Delete Sample2.xlsx!!!
  5. Open a New workbook and it's module paste this code and run Sample. You will notice that you will not get a prompt.

Code

Option Explicit

Sub Sample()
    getWorkbook "c:\Sample1.xlsx"
End Sub

Function getWorkbook(bkPath As String) As Workbook
    Application.AskToUpdateLinks = False
    Set getWorkbook = Workbooks.Open(bkPath, False)
    Application.AskToUpdateLinks = True
End Function

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Create procedure [dbo].[a]

@examdate varchar(10) ,
@examdate1 varchar(10)
AS
Select tbl.sno,mark,subject1,
Convert(varchar(10),examdate,103) from tbl
where 
(Convert(datetime,examdate,103)  >= Convert(datetime,@examdate,103) 
and (Convert(datetime,examdate,103) <=  Convert(datetime,@examdate1,103)))

Make an html number input always display 2 decimal places

Look into toFixed for Javascript numbers. You could write an onChange function for your number field that calls toFixed on the input and sets the new value.

jQuery access input hidden value

Most universal way is to take value by name. It doesn't matter if its input or select form element type.

var value = $('[name="foo"]');

How to get input field value using PHP

<form action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
<button type="submit" name="ok">OK</button>
</form>
<?php
if(isset($_POST['ok'])){
echo $_POST['subject'];
}
?>

Python "string_escape" vs "unicode_escape"

According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.

They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.

git: fatal: Could not read from remote repository

I encounter this issue by enter many times error password.

so I have to change the MaxAuthTries to a bigger number:

open the sshd_config in server end:

vim  /etc/ssh/sshd_config

change the MaxAuthTries number:

MaxAuthTries 100    # there I change to 100, you can change to a bigger than your current tries number

How do I redirect with JavaScript?

window.location.replace('http://sidanmor.com');

It's better than using window.location.href = 'http://sidanmor.com';

Using replace() is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use window.location.href

If you want to simulate an HTTP redirect, use window.location.replace

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");

// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";

Taken from here: How to redirect to another page in jQuery?

Remove leading or trailing spaces in an entire column of data

I was able to use Find & Replace with the "Find what:" input field set to:

" * "

(space asterisk space with no double-quotes)

and "Replace with:" set to:

""

(nothing)

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I came here because i had this problem and non of the answers here helped me. For future user that could be helped here:

My problem was I did two 9-patch images for a switch button. Then I rezized that image without 9-patching them. To solve the issue I had to 9-patch all the images for all the drawable folders (xxhdpi, xhdpi and so on)

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

When creating a Dockerfile, there are two commands that you can use to copy files/directories into it – ADD and COPY. Although there are slight differences in the scope of their function, they essentially perform the same task.

So, why do we have two commands, and how do we know when to use one or the other?

DOCKER ADD COMMAND

Let’s start by noting that the ADD command is older than COPY. Since the launch of the Docker platform, the ADD instruction has been part of its list of commands.

The command copies files/directories to a file system of the specified container.

The basic syntax for the ADD command is:

ADD <src> … <dest>

It includes the source you want to copy (<src>) followed by the destination where you want to store it (<dest>). If the source is a directory, ADD copies everything inside of it (including file system metadata).

For instance, if the file is locally available and you want to add it to the directory of an image, you type:

ADD /source/file/path  /destination/path

ADD can also copy files from a URL. It can download an external file and copy it to the wanted destination. For example:

ADD http://source.file/url  /destination/path

An additional feature is that it copies compressed files, automatically extracting the content in the given destination. This feature only applies to locally stored compressed files/directories.

ADD source.file.tar.gz /temp

Bear in mind that you cannot download and extract a compressed file/directory from a URL. The command does not unpack external packages when copying them to the local filesystem.

DOCKER COPY COMMAND

Due to some functionality issues, Docker had to introduce an additional command for duplicating content – COPY.

Unlike its closely related ADD command, COPY only has only one assigned function. Its role is to duplicate files/directories in a specified location in their existing format. This means that it doesn’t deal with extracting a compressed file, but rather copies it as-is.

The instruction can be used only for locally stored files. Therefore, you cannot use it with URLs to copy external files to your container.

To use the COPY instruction, follow the basic command format:

Type in the source and where you want the command to extract the content as follows:

COPY <src> … <dest> 

For example:

COPY /source/file/path  /destination/path 

Which command to use?(Best Practice)

Considering the circumstances in which the COPY command was introduced, it is evident that keeping ADD was a matter of necessity. Docker released an official document outlining best practices for writing Dockerfiles, which explicitly advises against using the ADD command.

Docker’s official documentation notes that COPY should always be the go-to instruction as it is more transparent than ADD.

If you need to copy from the local build context into a container, stick to using COPY.

The Docker team also strongly discourages using ADD to download and copy a package from a URL. Instead, it’s safer and more efficient to use wget or curl within a RUN command. By doing so, you avoid creating an additional image layer and save space.

Validate that end date is greater than start date with jQuery

Reference jquery.validate.js and jquery-1.2.6.js. Add a startDate class to your start date textbox. Add an endDate class to your end date textbox.

Add this script block to your page:-

<script type="text/javascript">
    $(document).ready(function() {
        $.validator.addMethod("endDate", function(value, element) {
            var startDate = $('.startDate').val();
            return Date.parse(startDate) <= Date.parse(value) || value == "";
        }, "* End date must be after start date");
        $('#formId').validate();
    });
</script>

Hope this helps :-)

how to call scalar function in sql server 2008

For Scalar Function Syntax is

Select dbo.Function_Name(parameter_name)

Select dbo.Department_Employee_Count('HR')

How to set selected item of Spinner by value, not by position?

As some of the previous answers are very right, I just want to make sure from none of you fall in such this problem.

If you set the values to the ArrayList using String.format, you MUST get the position of the value using the same string structure String.format.

An example:

ArrayList<String> myList = new ArrayList<>();
myList.add(String.format(Locale.getDefault() ,"%d", 30));
myList.add(String.format(Locale.getDefault(), "%d", 50));
myList.add(String.format(Locale.getDefault(), "%d", 70));
myList.add(String.format(Locale.getDefault(), "%d", 100));

You must get the position of needed value like this:

myList.setSelection(myAdapter.getPosition(String.format(Locale.getDefault(), "%d", 70)));

Otherwise, you'll get the -1, item not found!

I used Locale.getDefault() because of Arabic language.

I hope that will be helpful for you.

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

How to prevent sticky hover effects for buttons on touch devices

Add this JS code to your page:

document.body.className = 'ontouchstart' in document.documentElement ? '' : 'hover';

now in your CSS before every hover add the hover class like this:

.hover .foo:hover {}

If the device is touch, the body class will be empty, otherwise its class will be hover and the rules are applied!

Remove directory which is not empty

My modified answer from @oconnecp (https://stackoverflow.com/a/25069828/3027390)

Uses path.join for better cross-platform experience. So, don't forget to require it.

var path = require('path');

Also renamed function to rimraf ;)

/**
 * Remove directory recursively
 * @param {string} dir_path
 * @see https://stackoverflow.com/a/42505874/3027390
 */
function rimraf(dir_path) {
    if (fs.existsSync(dir_path)) {
        fs.readdirSync(dir_path).forEach(function(entry) {
            var entry_path = path.join(dir_path, entry);
            if (fs.lstatSync(entry_path).isDirectory()) {
                rimraf(entry_path);
            } else {
                fs.unlinkSync(entry_path);
            }
        });
        fs.rmdirSync(dir_path);
    }
}

How to test my servlet using JUnit

 public class WishServletTest {
 WishServlet wishServlet;
 HttpServletRequest mockhttpServletRequest;
 HttpServletResponse mockhttpServletResponse;

@Before
public void setUp(){
    wishServlet=new WishServlet();
    mockhttpServletRequest=createNiceMock(HttpServletRequest.class);
    mockhttpServletResponse=createNiceMock(HttpServletResponse.class);
}

@Test
public void testService()throws Exception{
    File file= new File("Sample.txt");
    File.createTempFile("ashok","txt");
    expect(mockhttpServletRequest.getParameter("username")).andReturn("ashok");
    expect(mockhttpServletResponse.getWriter()).andReturn(new PrintWriter(file));
    replay(mockhttpServletRequest);
    replay(mockhttpServletResponse);
    wishServlet.doGet(mockhttpServletRequest, mockhttpServletResponse);
    FileReader fileReader=new FileReader(file);
    int count = 0;
    String str = "";
    while ( (count=fileReader.read())!=-1){
        str=str+(char)count;
    }

    Assert.assertTrue(str.trim().equals("Helloashok"));
    verify(mockhttpServletRequest);
    verify(mockhttpServletResponse);

}

}

jQuery .attr("disabled", "disabled") not working in Chrome

Here:
http://jsbin.com/urize4/edit

Live Preview
http://jsbin.com/urize4/

You should use "readonly" instead like:

$("input[type='text']").attr("readonly", "true");

Make selected block of text uppercase

Without defining keyboard shortcuts

  1. Select the text you want capitalized

  2. Open View->Command Palette (or Shift+Command+P)

  3. Start typing "Transform to uppercase" and select that option

  4. Voila!

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

I came to this issue both on simulator and device.

And there is a tricky phenomenon. If I copy the project to a new place, there is some chance this issue gone when I first run. But after I clean and run, this issue comes.

I have try almost all the solution from the answers to this question, but neither do.

With the help of the version control system git, I can check out the previous version of the code and to see what modification lead to this issue.

In my project the HEAD version is workable, and my latest umcommitted modification will lead to this issue.

So I checkout each file from the workable version of my code to locate the issue. When I checkout the coin.xcodeproj/project.pbxproj(coin is my app name), this issue gone.

Solution: just checkout the workable coin.xcodeproj/project.pbxproj, for my case I just use the HEAD version is ok.

git checkout HEAD coin.xcodeproj/project.pbxproj


To make it a summary:

How to get the primary IP address of the local machine on Linux and OS X?

Edited (2014-06-01 2018-01-09)

For stronger config, with many interfaces and many IP configured on each interfaces, I wrote a pure bash script (not based on 127.0.0.1) for finding correct interface and ip, based on default route. I post this script at very bottom of this answer.

Intro

As both Os have installed by default, there is a bash tip for both Mac and Linux:

The locale issue is prevented by the use of LANG=C:

myip=
while IFS=$': \t' read -a line ;do
    [ -z "${line%inet}" ] && ip=${line[${#line[1]}>4?1:2]} &&
        [ "${ip#127.0.0.1}" ] && myip=$ip
  done< <(LANG=C /sbin/ifconfig)
echo $myip

Putting this into a function:

Minimal:

getMyIP() {
    local _ip _line
    while IFS=$': \t' read -a _line ;do
        [ -z "${_line%inet}" ] &&
           _ip=${_line[${#_line[1]}>4?1:2]} &&
           [ "${_ip#127.0.0.1}" ] && echo $_ip && return 0
      done< <(LANG=C /sbin/ifconfig)
}

Simple use:

getMyIP
192.168.1.37

Fancy tidy:

getMyIP() {
    local _ip _myip _line _nl=$'\n'
    while IFS=$': \t' read -a _line ;do
        [ -z "${_line%inet}" ] &&
           _ip=${_line[${#_line[1]}>4?1:2]} &&
           [ "${_ip#127.0.0.1}" ] && _myip=$_ip
      done< <(LANG=C /sbin/ifconfig)
    printf ${1+-v} $1 "%s${_nl:0:$[${#1}>0?0:1]}" $_myip
}

Usage:

getMyIP
192.168.1.37

or, running same function, but with an argument:

getMyIP varHostIP
echo $varHostIP
192.168.1.37
set | grep ^varHostIP
varHostIP=192.168.1.37

Nota: Without argument, this function output on STDOUT, the IP and a newline, with an argument, nothing is printed, but a variable named as argument is created and contain IP without newline.

Nota2: This was tested on Debian, LaCie hacked nas and MaxOs. If this won't work under your environ, I will be very interested by feed-backs!

Older version of this answer

( Not deleted because based on sed, not bash. )

Warn: There is an issue about locales!

Quick and small:

myIP=$(ip a s|sed -ne '/127.0.0.1/!{s/^[ \t]*inet[ \t]*\([0-9.]\+\)\/.*$/\1/p}')

Exploded (work too;)

myIP=$(
    ip a s |
    sed -ne '
        /127.0.0.1/!{
            s/^[ \t]*inet[ \t]*\([0-9.]\+\)\/.*$/\1/p
        }
    '
)

Edit:

How! This seem not work on Mac OS...

Ok, this seem work quite same on Mac OS as on my Linux:

myIP=$(LANG=C /sbin/ifconfig  | sed -ne $'/127.0.0.1/ ! { s/^[ \t]*inet[ \t]\\{1,99\\}\\(addr:\\)\\{0,1\\}\\([0-9.]*\\)[ \t\/].*$/\\2/p; }')

splitted:

myIP=$(
    LANG=C /sbin/ifconfig  |
        sed -ne $'/127.0.0.1/ ! {
            s/^[ \t]*inet[ \t]\\{1,99\\}\\(addr:\\)\\{0,1\\}\\([0-9.]*\\)[ \t\/].*$/\\2/p;
        }')

My script (jan 2018):

This script will first find your default route and interface used for, then search for local ip matching network of gateway and populate variables. The last two lines just print, something like:

Interface   : en0
Local Ip    : 10.2.5.3
Gateway     : 10.2.4.204
Net mask    : 255.255.252.0
Run on mac  : true

or

Interface   : eth2
Local Ip    : 192.168.1.31
Gateway     : 192.168.1.1
Net mask    : 255.255.255.0
Run on mac  : false

Well, there it is:

#!/bin/bash
runOnMac=false
int2ip() { printf ${2+-v} $2 "%d.%d.%d.%d" \
        $(($1>>24)) $(($1>>16&255)) $(($1>>8&255)) $(($1&255)) ;}
ip2int() { local _a=(${1//./ }) ; printf ${2+-v} $2 "%u" $(( _a<<24 |
                  ${_a[1]} << 16 | ${_a[2]} << 8 | ${_a[3]} )) ;}
while IFS=$' :\t\r\n' read a b c d; do
    [ "$a" = "usage" ] && [ "$b" = "route" ] && runOnMac=true
    if $runOnMac ;then
        case $a in 
            gateway )    gWay=$b  ;;
            interface )  iFace=$b ;;
        esac
    else
        [ "$a" = "0.0.0.0" ] && [ "$c" = "$a" ] && iFace=${d##* } gWay=$b
    fi
done < <(/sbin/route -n 2>&1 || /sbin/route -n get 0.0.0.0/0)
ip2int $gWay gw
while read lhs rhs; do
    [ "$lhs" ] && { 
        [ -z "${lhs#*:}" ] && iface=${lhs%:}
        [ "$lhs" = "inet" ] && [ "$iface" = "$iFace" ] && {
            mask=${rhs#*netmask }
            mask=${mask%% *}
            [ "$mask" ] && [ -z "${mask%0x*}" ] &&
                printf -v mask %u $mask ||
                ip2int $mask mask
            ip2int ${rhs%% *} ip
            (( ( ip & mask ) == ( gw & mask ) )) &&
                int2ip $ip myIp && int2ip $mask netMask
        }
    }
done < <(/sbin/ifconfig)
printf "%-12s: %s\n" Interface $iFace Local\ Ip $myIp \
       Gateway $gWay Net\ mask $netMask Run\ on\ mac $runOnMac

Chrome disable SSL checking for sites?

To disable the errors windows related with certificates you can start Chrome from console and use this option: --ignore-certificate-errors.

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --ignore-certificate-errors

You should use it for testing purposes. A more complete list of options is here: http://peter.sh/experiments/chromium-command-line-switches/

How do I concatenate two strings in Java?

"+" not "."

But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.

malloc for struct and pointer in C

First malloc allocates memory for struct, including memory for x (pointer to double). Second malloc allocates memory for double value wtich x points to.

Why does modulus division (%) only work with integers?

The % operator gives you a REMAINDER(another name for modulus) of a number. For C/C++, this is only defined for integer operations. Python is a little broader and allows you to get the remainder of a floating point number for the remainder of how many times number can be divided into it:

>>> 4 % math.pi
0.85840734641020688
>>> 4 - math.pi
0.85840734641020688
>>> 

How to remove item from list in C#?

resultList = results.Where(x=>x.Id != 2).ToList();

There's a little Linq helper I like that's easy to implement and can make queries with "where not" conditions a little easier to read:

public static IEnumerable<T> ExceptWhere<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
    return source.Where(x=>!predicate(x));
}

//usage in above situation
resultList = results.ExceptWhere(x=>x.Id == 2).ToList();

making a paragraph in html contain a text from a file

Javascript will do the trick here.

function load() {
    var file = new XMLHttpRequest();
    file.open("GET", "http://remote.tld/random.txt", true);
    file.onreadystatechange = function() {
      if (file.readyState === 4) {  // Makes sure the document is ready to parse
        if (file.status === 200) {  // Makes sure it's found the file
          text = file.responseText;
          document.getElementById("div1").innerHTML = text;
        }
      }
    }
}

window.onLoad = load();

Xcode error "Could not find Developer Disk Image"

There actually is a way to deploy to a device running a newer iOS that the particular version of Xcode might not actually support. What you need to do is copy over the folder that contains the Developer Disk Image from the newer version of Xcode.

For example, you can deploy to a device running iOS 9.3 using Xcode 7.2.1 (which only supports up to iOS 9.2) using this method. Go to the Xcode 7.3 install and navigate to:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

From here, copy over the folder that contains the version you are trying to run on the older version of Xcode (for this example, it's 9.3 with the build number in parenthesis). Copy this folder over to the other install of Xcode, and now you should be able to deploy to a device running that particular version of iOS.

This will fail, however, if you're utilizing API calls that were specifically added to the newer version of the SDK. In that case, you will be forced to update Xcode.

"Too many characters in character literal error"

This is because, in C#, single quotes ('') denote (or encapsulate) a single character, whereas double quotes ("") are used for a string of characters. For example:

var myChar = '=';

var myString = "==";

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Not sure if anyone is having the same responsive issue, but it was just a simple css solution for me.

same example

...  ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"> ...
...  div collapse="isCollapsed"> ...

with

@media screen and (min-width: 768px) {
    .collapse{
        display: block !important;
    }
}

Which ORM should I use for Node.js and MySQL?

May I suggest Node ORM?

https://github.com/dresende/node-orm2

There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.

MongoDB is available since version 2.1.x (released in July 2013)

UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize

How to search in an array with preg_match?

Use preg_grep

$array = preg_grep(
    '/(my\n+string\n+)/i',
    array( 'file' , 'my string  => name', 'this')
);

Sort a single String in Java

toCharArray followed by Arrays.sort followed by a String constructor call:

import java.util.Arrays;

public class Test
{
    public static void main(String[] args)
    {
        String original = "edcba";
        char[] chars = original.toCharArray();
        Arrays.sort(chars);
        String sorted = new String(chars);
        System.out.println(sorted);
    }
}

EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.

How do I apply the for-each loop to every character in a String?

You can also use a lambda in this case.

    String s = "xyz";
    IntStream.range(0, s.length()).forEach(i -> {
        char c = s.charAt(i);
    });

How to join multiple lines of file names into one with custom delimiter?

To avoid potential newline confusion for tr we could add the -b flag to ls:

ls -1b | tr '\n' ';'

How to find Oracle Service Name

Connect to the server as "system" using SID. Execute this query:

select value from v$parameter where name like '%service_name%';

It worked for me.

Can I set max_retries for requests.request?

It is the underlying urllib3 library that does the retrying. To set a different maximum retry count, use alternative transport adapters:

from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=5))

The max_retries argument takes an integer or a Retry() object; the latter gives you fine-grained control over what kinds of failures are retried (an integer value is turned into a Retry() instance which only handles connection failures; errors after a connection is made are by default not handled as these could lead to side-effects).


Old answer, predating the release of requests 1.2.1:

The requests library doesn't really make this configurable, nor does it intend to (see this pull request). Currently (requests 1.1), the retries count is set to 0. If you really want to set it to a higher value, you'll have to set this globally:

import requests

requests.adapters.DEFAULT_RETRIES = 5

This constant is not documented; use it at your own peril as future releases could change how this is handled.

Update: and this did change; in version 1.2.1 the option to set the max_retries parameter on the HTTPAdapter() class was added, so that now you have to use alternative transport adapters, see above. The monkey-patch approach no longer works, unless you also patch the HTTPAdapter.__init__() defaults (very much not recommended).

Set cookies for cross origin requests

Note for Chrome Browser released in 2020.

A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure.

So if your backend server does not set SameSite=None, Chrome will use SameSite=Lax by default and will not use this cookie with { withCredentials: true } requests.

More info https://www.chromium.org/updates/same-site.

Firefox and Edge developers also want to release this feature in the future.

Spec found here: https://tools.ietf.org/html/draft-west-cookie-incrementalism-01#page-8

Are HTTP headers case-sensitive?

officially, headers are case insensitive, however, it is common practice to capitalize the first letter of every word.
but, because it is common practice, certain programs like IE assume the headers are capitalized.
so while the docs say the are case insensitive, bad programmers have basically changed the docs.

Xcode 4 - "Archive" is greyed out?

As the other answers state, you need to select an active scheme to something that is not a simulator, i.e. a device that's connected to your mac.

If you have no device connected to the mac then selecting "Generic IOS Device" works also.

enter image description here

How do I sleep for a millisecond in Perl?

A quick googling on "perl high resolution timers" gave a reference to Time::HiRes. Maybe that it what you want.

Angular update object in object array

updateValue(data){    
     // retriving index from array
     let indexValue = this.items.indexOf(data);
    // changing specific element in array
     this.items[indexValue].isShow =  !this.items[indexValue].isShow;
}

invalid byte sequence for encoding "UTF8"

I had the same problem: my file was not encoded as UTF-8. I have solved it by opening the file with notepad++ and changing the encoding of the file.

Go to "Encoding" and select "Convert to UTF-8". Save changes and that's all!

How do I pull from a Git repository through an HTTP proxy?

I got around the proxy using https... some proxies don't even check https.

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

c:\git\meantest>git clone http://github.com/linnovate/mean.git
Cloning into 'mean'...
fatal: unable to access 'http://github.com/linnovate/mean.git/': Failed connect
to github.com:80; No error

c:\git\meantest>git clone https://github.com/linnovate/mean.git
Cloning into 'mean'...
remote: Reusing existing pack: 2587, done.
remote: Counting objects: 27, done.
remote: Compressing objects: 100% (24/24), done.
rRemote: Total 2614 (delta 3), reused 4 (delta 0)eceiving objects:  98% (2562/26

Receiving objects: 100% (2614/2614), 1.76 MiB | 305.00 KiB/s, done.
Resolving deltas: 100% (1166/1166), done.
Checking connectivity... done

How to return JSon object

You only have one row to serialize. Try something like this :

List<results> resultRows = new List<results>

resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});

string json = JavaScriptSerializer.Serialize(new { results = resultRows});
  • Edit to match OP's original json output

** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}

Write to file, but overwrite it if it exists

Despite NylonSmile's answer, which is "sort of" correct.. I was unable to overwrite files, in this manner..

echo "i know about Pipes, girlfriend" > thatAnswer

zsh: file exists: thatAnswer

to solve my issues.. I had to use... >!, á la..

[[ $FORCE_IT == 'YES' ]] && echo "$@" >! "$X" || echo "$@" > "$X"

Obviously, be careful with this...

How do I get logs/details of ansible-playbook module executions?

There is also other way to generate log file.

Before running ansible-playbook run the following commands to enable logging:

  • Specify the location for the log file.

    export ANSIBLE_LOG_PATH=~/ansible.log

  • Enable Debug

    export ANSIBLE_DEBUG=True

  • To check that generated log file.

    less $ANSIBLE_LOG_PATH

how to parse xml to java object?

I find jackson fasterxml is one good choice to serializing/deserializing bean with XML.

Refer: How to use spring to marshal and unmarshal xml?

Difference between a Seq and a List in Scala

Seq is a trait that List implements.

If you define your container as Seq, you can use any container that implements Seq trait.

scala> def sumUp(s: Seq[Int]): Int = { s.sum }
sumUp: (s: Seq[Int])Int

scala> sumUp(List(1,2,3))
res41: Int = 6

scala> sumUp(Vector(1,2,3))
res42: Int = 6

scala> sumUp(Seq(1,2,3))
res44: Int = 6

Note that

scala> val a = Seq(1,2,3)
a: Seq[Int] = List(1, 2, 3)

Is just a short hand for:

scala> val a: Seq[Int] = List(1,2,3)
a: Seq[Int] = List(1, 2, 3)

if the container type is not specified, the underlying data structure defaults to List.

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

javascript cell number validation

If you type:

if { number.value.length!= 10}...     

It will sure work because the value is the quantity which will be driven from the object.

Default parameters with C++ constructors

Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor.

One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out this thread for more info.

How to assign string to bytes array

Piece of cake:

arr := []byte("That's all folks!!")

bypass invalid SSL certificate in .net core

I faced off the same problem when working with self-signed certs and client cert auth on .NET Core 2.2 and Docker Linux containers. Everything worked fine on my dev Windows machine, but in Docker I got such error:

System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure

Fortunately, the certificate was generated using a chain. Of course, you can always ignore this solution and use the above solutions.

So here is my solution:

  1. I saved the certificate using Chrome on my computer in P7B format.

  2. Convert certificate to PEM format using this command:
    openssl pkcs7 -inform DER -outform PEM -in <cert>.p7b -print_certs > ca_bundle.crt

  3. Open the ca_bundle.crt file and delete all Subject recordings, leaving a clean file. Example below:

    -----BEGIN CERTIFICATE-----
    _BASE64 DATA_
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    _BASE64 DATA_
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    _BASE64 DATA_
    -----END CERTIFICATE-----
  1. Put these lines to the Dockerfile (in the final steps):
    # Update system and install curl and ca-certificates
    RUN apt-get update && apt-get install -y curl && apt-get install -y ca-certificates
    # Copy your bundle file to the system trusted storage
    COPY ./ca_bundle.crt /usr/local/share/ca-certificates/ca_bundle.crt
    # During docker build, after this line you will get such output: 1 added, 0 removed; done.
    RUN update-ca-certificates
  1. In the app:
    var address = new EndpointAddress("https://serviceUrl");                
    var binding = new BasicHttpsBinding
    {
        CloseTimeout = new TimeSpan(0, 1, 0),
        OpenTimeout = new TimeSpan(0, 1, 0),
        ReceiveTimeout = new TimeSpan(0, 1, 0),
        SendTimeout = new TimeSpan(0, 1, 0),
        MaxBufferPoolSize = 524288,
        MaxBufferSize = 65536,
        MaxReceivedMessageSize = 65536,
        TextEncoding = Encoding.UTF8,
        TransferMode = TransferMode.Buffered,
        UseDefaultWebProxy = true,
        AllowCookies = false,
        BypassProxyOnLocal = false,
        ReaderQuotas = XmlDictionaryReaderQuotas.Max,
        Security =
        {
            Mode = BasicHttpsSecurityMode.Transport,
            Transport = new HttpTransportSecurity
            {
                ClientCredentialType = HttpClientCredentialType.Certificate,
                ProxyCredentialType = HttpProxyCredentialType.None
            }
        }
    };
    var client = new MyWSClient(binding, address);
    client.ClientCredentials.ClientCertificate.Certificate = GetClientCertificate("clientCert.pfx", "passwordForClientCert");
    // Client certs must be installed
    client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication
    {
        CertificateValidationMode = X509CertificateValidationMode.ChainTrust,
        TrustedStoreLocation = StoreLocation.LocalMachine,
        RevocationMode = X509RevocationMode.NoCheck
    };

GetClientCertificate method:

private static X509Certificate2 GetClientCertificate(string clientCertName, string password)
{
    //Create X509Certificate2 object from .pfx file
    byte[] rawData = null;
    using (var f = new FileStream(Path.Combine(AppContext.BaseDirectory, clientCertName), FileMode.Open, FileAccess.Read))
    {
        var size = (int)f.Length;
        var rawData = new byte[size];
        f.Read(rawData, 0, size);
        f.Close();
    }
    return new X509Certificate2(rawData, password);
}

Gradle build without tests

gradle build -x test --parallel

If your machine has multiple cores. However, it is not recommended to use parallel clean.

How to delete the contents of a folder?

I'm surprised nobody has mentioned the awesome pathlib to do this job.

If you only want to remove files in a directory it can be a oneliner

from pathlib import Path

[f.unlink() for f in Path("/path/to/folder").glob("*") if f.is_file()] 

To also recursively remove directories you can write something like this:

from pathlib import Path
from shutil import rmtree

for path in Path("/path/to/folder").glob("**/*"):
    if path.is_file():
        path.unlink()
    elif path.is_dir():
        rmtree(path)

Ajax call Into MVC Controller- Url Issue

Starting from Rob's answer, I am currently using the following syntax.Since the question has received a lot of attention,I decided to share it with you :

var requrl = '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)';
  $.ajax({
   type: "POST",
   url: requrl,
   data: "{queryString:'" + searchVal + "'}",
   contentType: "application/json; charset=utf-8",
   dataType: "html",
   success: function (data) {
   alert("here" + data.d.toString());
   }
  });

JS how to cache a variable

Use localStorage for that. It's persistent over sessions.

Writing :

localStorage['myKey'] = 'somestring'; // only strings

Reading :

var myVar = localStorage['myKey'] || 'defaultValue';

If you need to store complex structures, you might serialize them in JSON. For example :

Reading :

var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

Writing :

localStorage['myKey'] = JSON.stringify(myVar);

Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

Difference Between One-to-Many, Many-to-One and Many-to-Many?

1) The circles are Entities/POJOs/Beans

2) deg is an abbreviation for degree as in graphs (number of edges)

PK=Primary key, FK=Foreign key

Note the contradiction between the degree and the name of the side. Many corresponds to degree=1 while One corresponds to degree >1.

Illustration of one-to-many many-to-one

ViewPager PagerAdapter not updating the View

This is a horrible problem and I'm happy to present an excellent solution; simple, efficient, and effective !

See below, the code shows using a flag to indicate when to return POSITION_NONE

public class ViewPagerAdapter extends PagerAdapter
{
    // Members
    private boolean mForceReinstantiateItem = false;

    // This is used to overcome terrible bug that Google isn't fixing
    // We know that getItemPosition() is called right after notifyDataSetChanged()
    // Therefore, the fix is to return POSITION_NONE right after the notifyDataSetChanged() was called - but only once
    @Override
    public int getItemPosition(Object object)
    {
        if (mForceReinstantiateItem)
        {
            mForceReinstantiateItem = false;
            return POSITION_NONE;
        }
        else
        {
            return super.getItemPosition(object);
        }
    }

    public void setData(ArrayList<DisplayContent> newContent)
    {
        mDisplayContent = newContent;
        mForceReinstantiateItem = true;
        notifyDataSetChanged();
    }

}

Importing csv file into R - numeric values read as characters

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

JavaScript calculate the day of the year (1 - 366)

Math.floor((Date.now() - Date.parse(new Date().getFullYear(), 0, 0)) / 86400000)

this is my solution

How to query SOLR for empty fields?

One caveat! If you want to compose this via OR or AND you cannot use it in this form:

-myfield:*

but you must use

(*:* NOT myfield:*)

This form is perfectly composable. Apparently SOLR will expand the first form to the second, but only when it is a top node. Hope this saves you some time!

Adding line break in C# Code behind page

 result = "Minimum MarketData"+ Environment.NewLine
           + "Refresh interval is 1";

IIS7: Setup Integrated Windows Authentication like in IIS6

So do you want them to get the IE password-challenge box, or should they be directed to your login page and enter their information there? If it's the second option, then you should at least enable Anonymous access to your login page, since the site won't know who they are yet.

If you want the first option, then the login page they're getting forwarded to will need to read the currently logged-in user and act based on that, since they would have had to correctly authenticate to get this far.

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Well, I totally agree with answers already exist on this point:

  • bootstrap.yml is used to save parameters that point out where the remote configuration is and Bootstrap Application Context is created with these remote configuration.

Actually, it is also able to store normal properties just the same as what application.yml do. But pay attention on this tricky thing:

  • If you do place properties in bootstrap.yml, they will get lower precedence than almost any other property sources, including application.yml. As described here.

Let's make it clear, there are two kinds of properties related to bootstrap.yml:

  • Properties that are loaded during the bootstrap phase. We use bootstrap.yml to find the properties holder (A file system, git repository or something else), and the properties we get in this way are with high precedence, so they cannot be overridden by local configuration. As described here.
  • Properties that are in the bootstrap.yml. As explained early, they will get lower precedence. Use them to set defaults maybe a good idea.

So the differences between putting a property on application.yml or bootstrap.yml in spring boot are:

  • Properties for loading configuration files in bootstrap phase can only be placed in bootstrap.yml.
  • As for all other kinds of properties, place them in application.yml will get higher precedence.

What is the significance of #pragma marks? Why do we need #pragma marks?

While searching for doc to point to about how pragma are directives for the compiler, I found this NSHipster article that does the job pretty well.

I hope you'll enjoy the reading

Page redirect after certain time PHP

header( "refresh:5;url=wherever.php" );

this is the php way to set header which will redirect you to wherever.php in 5 seconds


Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file. (source php.net)

How do I list all the columns in a table?

SQL Server

To list all the user defined tables of a database:

use [databasename]
select name from sysobjects where type = 'u'

To list all the columns of a table:

use [databasename]
select name from syscolumns where id=object_id('tablename')

Expression must have class type

Allow an analysis.

#include <iostream>   // not #include "iostream"
using namespace std;  // in this case okay, but never do that in header files

class A
{
 public:
  void f() { cout<<"f()\n"; }
};

int main()
{
 /*
 // A a; //this works
 A *a = new A(); //this doesn't
 a.f(); // "f has not been declared"
 */ // below


 // system("pause");  <-- Don't do this. It is non-portable code. I guess your 
 //                       teacher told you this?
 //                       Better: In your IDE there is prolly an option somewhere
 //                               to not close the terminal/console-window.
 //                       If you compile on a CLI, it is not needed at all.
}

As a general advice:

0) Prefer automatic variables
  int a;
  MyClass myInstance;
  std::vector<int> myIntVector;

1) If you need data sharing on big objects down 
   the call hierarchy, prefer references:

  void foo (std::vector<int> const &input) {...}
  void bar () { 
       std::vector<int> something;
       ...
       foo (something);
  }


2) If you need data sharing up the call hierarchy, prefer smart-pointers
   that automatically manage deletion and reference counting.

3) If you need an array, use std::vector<> instead in most cases.
   std::vector<> is ought to be the one default container.

4) I've yet to find a good reason for blank pointers.

   -> Hard to get right exception safe

       class Foo {
           Foo () : a(new int[512]), b(new int[512]) {}
           ~Foo() {
               delete [] b;
               delete [] a;
           }
       };

       -> if the second new[] fails, Foo leaks memory, because the
          destructor is never called. Avoid this easily by using 
          one of the standard containers, like std::vector, or
          smart-pointers.

As a rule of thumb: If you need to manage memory on your own, there is generally a superiour manager or alternative available already, one that follows the RAII principle.

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

For those that are not overflowing but hiding by negative margin:

$('#element').height() + -parseInt($('#element').css("margin-top"));

(ugly but only one that works so far)

How can I add or update a query string parameter?

I realize this question is old and has been answered to death, but here's my stab at it. I'm trying to reinvent the wheel here because I was using the currently accepted answer and the mishandling of URL fragments recently bit me in a project.

The function is below. It's quite long, but it was made to be as resilient as possible. I would love suggestions for shortening/improving it. I put together a small jsFiddle test suite for it (or other similar functions). If a function can pass every one of the tests there, I say it's probably good to go.

Update: I came across a cool function for using the DOM to parse URLs, so I incorporated that technique here. It makes the function shorter and more reliable. Props to the author of that function.

/**
 * Add or update a query string parameter. If no URI is given, we use the current
 * window.location.href value for the URI.
 * 
 * Based on the DOM URL parser described here:
 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
 *
 * @param   (string)    uri     Optional: The URI to add or update a parameter in
 * @param   (string)    key     The key to add or update
 * @param   (string)    value   The new value to set for key
 *
 * Tested on Chrome 34, Firefox 29, IE 7 and 11
 */
function update_query_string( uri, key, value ) {

    // Use window URL if no query string is provided
    if ( ! uri ) { uri = window.location.href; }

    // Create a dummy element to parse the URI with
    var a = document.createElement( 'a' ), 

        // match the key, optional square brackets, an equals sign or end of string, the optional value
        reg_ex = new RegExp( key + '((?:\\[[^\\]]*\\])?)(=|$)(.*)' ),

        // Setup some additional variables
        qs,
        qs_len,
        key_found = false;

    // Use the JS API to parse the URI 
    a.href = uri;

    // If the URI doesn't have a query string, add it and return
    if ( ! a.search ) {

        a.search = '?' + key + '=' + value;

        return a.href;
    }

    // Split the query string by ampersands
    qs = a.search.replace( /^\?/, '' ).split( /&(?:amp;)?/ );
    qs_len = qs.length; 

    // Loop through each query string part
    while ( qs_len > 0 ) {

        qs_len--;

        // Remove empty elements to prevent double ampersands
        if ( ! qs[qs_len] ) { qs.splice(qs_len, 1); continue; }

        // Check if the current part matches our key
        if ( reg_ex.test( qs[qs_len] ) ) {

            // Replace the current value
            qs[qs_len] = qs[qs_len].replace( reg_ex, key + '$1' ) + '=' + value;

            key_found = true;
        }
    }   

    // If we haven't replaced any occurrences above, add the new parameter and value
    if ( ! key_found ) { qs.push( key + '=' + value ); }

    // Set the new query string
    a.search = '?' + qs.join( '&' );

    return a.href;
}

How to Convert Boolean to String

boolval() works for complicated tables where declaring variables and adding loops and filters do not work. Example:

$result[$row['name'] . "</td><td>" . (boolval($row['special_case']) ? 'True' : 'False') . "</td><td>" . $row['more_fields'] = $tmp

where $tmp is a key used in order to transpose other data. Here, I wanted the table to display "Yes" for 1 and nothing for 0, so used (boolval($row['special_case']) ? 'Yes' : '').

Custom thread pool in Java 8 parallel stream

you can try implementing this ForkJoinWorkerThreadFactory and inject it to Fork-Join class.

public ForkJoinPool(int parallelism,
                        ForkJoinWorkerThreadFactory factory,
                        UncaughtExceptionHandler handler,
                        boolean asyncMode) {
        this(checkParallelism(parallelism),
             checkFactory(factory),
             handler,
             asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
             "ForkJoinPool-" + nextPoolId() + "-worker-");
        checkPermission();
    }

you can use this constructor of Fork-Join pool to do this.

notes:-- 1. if you use this, take into consideration that based on your implementation of new threads, scheduling from JVM will be affected, which generally schedules fork-join threads to different cores(treated as a computational thread). 2. task scheduling by fork-join to threads won't get affected. 3. Haven't really figured out how parallel stream is picking threads from fork-join(couldn't find proper documentation on it), so try using a different threadNaming factory so as to make sure, if threads in parallel stream are being picked from customThreadFactory that you provide. 4. commonThreadPool won't use this customThreadFactory.

Remove background drawable programmatically in Android

I have a case scenario and I tried all the answers from above, but always new image was created on top of the old one. The solution that worked for me is:

imageView.setImageResource(R.drawable.image);

What do $? $0 $1 $2 mean in shell script?

They are called the Positional Parameters.

3.4.1 Positional Parameters

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.

Vertical Align Center in Bootstrap 4

Place your content within a flexbox container that is 100% high i.e h-100. Then justify the content centrally by using justify-content-center class.

<section class="container h-100 d-flex justify-content-center">
    <div class="jumbotron my-auto">
        <h1 class="display-3">Hello, Malawi!</h1>
    </div>
</section>

SQL string value spanning multiple lines in query

with your VARCHAR, you may also need to specify the length, or its usually good to

What about grabbing the text, making a sting of it, then putting it into the query witrh

String TableName = "ComplicatedTableNameHere";  
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere); 
String editTextString1 = editText1.getText().toString();  

BROKEN DOWN

String TableName = "ComplicatedTableNameHere";            
    //sets the table name as a string so you can refer to TableName instead of writing out your table name everytime

EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere); 
    //gets the text from your edit text fieldfield 
    //editText1 = your edit text name
    //EditTextIDhere = the id of your text field

String editTextString1 = editText1.getText().toString();  
    //sets the edit text as a string
    //editText1 is the name of the Edit text from the (EditText) we defined above
    //editTextString1 = the string name you will refer to in future

then use

       /* Insert data to a Table*/
       myDB.execSQL("INSERT INTO "
         + TableName
         + " (Column_Name, Column_Name2, Column_Name3, Column_Name4)"
         + " VALUES ( "+EditTextString1+", 'Column_Value2','Column_Value3','Column_Value4');");

Hope this helps some what...

NOTE each string is within

'"+stringname+"'

its the 'and' that enable the multi line element of the srting, without it you just get the first line, not even sure if you get the whole line, it may just be the first word

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

cmake - find_library - custom library location

Use CMAKE_PREFIX_PATH by adding multiple paths (separated by semicolons and no white spaces). You can set it as an environmental variable to avoid having absolute paths in your cmake configuration files

Notice that cmake will look for config file in any of the following folders where is any of the path in CMAKE_PREFIX_PATH and name is the name of the library you are looking for

<prefix>/                                               (W)
<prefix>/(cmake|CMake)/                                 (W)
<prefix>/<name>*/                                       (W)
<prefix>/<name>*/(cmake|CMake)/                         (W)
<prefix>/(lib/<arch>|lib|share)/cmake/<name>*/          (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/                (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/  (U)

In your case you need to add to CMAKE_PREFIX_PATH the following two paths:

D:/develop/cmake/libs/libA;D:/develop/cmake/libB

How to find whether or not a variable is empty in Bash?

This will return true if a variable is unset or set to the empty string ("").

if [ -z "$MyVar" ]
then
   echo "The variable MyVar has nothing in it."
elif ! [ -z "$MyVar" ]
then
   echo "The variable MyVar has something in it."
fi

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

I have exactly the same question and have done the same things as you with no success.

I found an entries in my log of

HM: HMR3Init: Falling back to raw-mode: VT-x is not available
VMSetError: F:\tinderbox\win-5.2\src\VBox\VMM\VMMR3\VM.cpp(361) int __cdecl 
VMR3Create(unsigned int,const struct VMM2USERMETHODS *,void (__cdecl *)(struct UVM *,void *,int,const char *,unsigned int,const char *,const char *,char *),void *,int (__cdecl *)(struct UVM *,struct VM *,void *),void *,struct VM **,struct UVM **); rc=VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT
00:00:05.088846 
VMSetError: Raw-mode is unavailable courtesy of Hyper-V. 00:00:05.089946 

ERROR [COM]: aRC=E_FAIL (0x80004005) aIID={872da645-4a9b-1727-bee2-5585105b9eed} aComponent={ConsoleWrap} aText={Raw-mode is unavailable courtesy of Hyper-V. (VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT)}, preserve=false aResultDetail=0 00:00:05.090271 Console: Machine state changed to 'PoweredOff'

My chip says it has VT-x and is on in the Bios but the log says not
HM: HMR3Init: Falling back to raw-mode: VT-x is not available I have a 6 month old Lenovo Yoga with 2.7-GHz Intel Core i7-7500U


I have tried the following, but it didn't work for me.

From this thread https://forums.virtualbox.org/viewtopic.php?t=77120#p383348 I tried disabling Device Guard but Windows wouldn't shut down so I reenabled it.

I used this path .... On the host operating system, click Start > Run, type gpedit.msc, and click Ok. The Local group Policy Editor opens. Go to Local Computer Policy > Computer Configuration > Administrative Templates > System > Device Guard > Turn on Virtualization Based Security. Select Disabled.

Disabling of EditText in Android

As android:editable="false" deprecated In xml

Use android:enabled="false" it's simple. Why use more code?

If you want in java class you can also use this programmatically

 editText.setEnabled(false);

accessing a variable from another class

Filename=url.java

public class url {

    public static final String BASEURL = "http://192.168.1.122/";

}

if u want to call the variable just use this:

url.BASEURL + "your code here";

Sql server - log is full due to ACTIVE_TRANSACTION

Here is what I ended up doing to work around the error.

First, I set up the database recovery model as SIMPLE. More information here.

Then, by deleting some old files I was able to make 5GB of free space which gave the log file more space to grow.

I reran the DELETE statement sucessfully without any warning.

I thought that by running the DELETE statement the database would inmediately become smaller thus freeing space in my hard drive. But that was not true. The space freed after a DELETE statement is not returned to the operating system inmediatedly unless you run the following command:

DBCC SHRINKDATABASE (MyDb, 0);
GO

More information about that command here.

Accessing an array out of bounds gives no error, why?

You are certainly overwriting your stack, but the program is simple enough that effects of this go unnoticed.

alternative to "!is.null()" in R

I have also seen:

if(length(obj)) {
  # do this if object has length
  # NULL has no length
}

I don't think it's great though. Because some vectors can be of length 0. character(0), logical(0), integer(0) and that might be treated as a NULL instead of an error.

Difference between the Apache HTTP Server and Apache Tomcat?

Well, Apache is HTTP webserver, where as Tomcat is also webserver for Servlets and JSP. Moreover Apache is preferred over Apache Tomcat in real time

How to get the day of week and the month of the year?

You can look at datejs which parses the localized date output for example.

The formatting may look like this, in your example:

new Date().toString('dddd, d MMMM yyyy at HH:mm:ss') 

Order by multiple columns with Doctrine

You have to add the order direction right after the column name:

$qb->orderBy('column1 ASC, column2 DESC');

As you have noted, multiple calls to orderBy do not stack, but you can make multiple calls to addOrderBy:

$qb->addOrderBy('column1', 'ASC')
   ->addOrderBy('column2', 'DESC');

How to change ViewPager's page?

slide to right

viewPager.arrowScroll(View.FOCUS_RIGHT);

slide to left

viewPager.arrowScroll(View.FOCUS_LEFT);

Changing API level Android Studio

In build.gradle change minSdkVersion 13 to minSdkVersion 8 Thats all you need to do. I solved my problem by only doing this.

defaultConfig {
    applicationId "com.example.sabrim.sbrtest"
    minSdkVersion 8
    targetSdkVersion 20
    versionCode 1
    versionName "1.0"
}

How to get the difference between two arrays of objects in JavaScript

import differenceBy from 'lodash/differenceBy'

const myDifferences = differenceBy(Result1, Result2, 'value')

This will return the difference between two arrays of objects, using the key value to compare them. Note two things with the same value will not be returned, as the other keys are ignored.

This is a part of lodash.

Goal Seek Macro with Goal as a Formula

GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.

The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.

I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).

For the test, I set:

  the GoalSeek cell  H18 = (G18^3)+(3*G18^2)+6
  the Goal cell      H32 =  11
  the ChangingCell   G18 =  0 

The code was:

Sub GSeek()
    With Worksheets("Sheet1")
        .Range("H18").GoalSeek _
        Goal:=.Range("H32").Value, _
        ChangingCell:=.Range("G18")
    End With
End Sub

And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.

HTML button to NOT submit form

I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.

<button type="button">My Button</button>

Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):

The missing value default and invalid value default are the Submit Button state.

CSS selector for text input fields?

input[type=text]

This will select all the input type text in a web-page.

How do you get the current time of day?

DateTime.Now.TimeOfDay gives it to you as a TimeSpan (from midnight).

DateTime.Now.ToString("h:mm:ss tt") gives it to you as a string.

DateTime reference: https://msdn.microsoft.com/en-us/library/system.datetime

Angular @ViewChild() error: Expected 2 arguments, but got 1

Use this

@ViewChild(ChildDirective, {static: false}) Component

psycopg2: insert multiple rows with one query

The cursor.copyfrom solution as provided by @jopseph.sheedy (https://stackoverflow.com/users/958118/joseph-sheedy) above (https://stackoverflow.com/a/30721460/11100064) is indeed lightning fast.

However, the example he gives are not generically usable for a record with any number of fields and it took me while to figure out how to use it correctly.

The IteratorFile needs to be instantiated with tab-separated fields like this (r is a list of dicts where each dict is a record):

    f = IteratorFile("{0}\t{1}\t{2}\t{3}\t{4}".format(r["id"],
        r["type"],
        r["item"],
        r["month"],
        r["revenue"]) for r in records)

To generalise for an arbitrary number of fields we will first create a line string with the correct amount of tabs and field placeholders : "{}\t{}\t{}....\t{}" and then use .format() to fill in the field values : *list(r.values())) for r in records:

        line = "\t".join(["{}"] * len(records[0]))

        f = IteratorFile(line.format(*list(r.values())) for r in records)

complete function in gist here.

How to convert an array of key-value tuples into an object

I much more recommend you to use ES6 with it's perfect Object.assign() method.

Object.assign({}, ...array.map(([ key, value ]) => ({ [key]: value })));

What happening here - Object.assign() do nothing but take key:value from donating object and puts pair in your result. In this case I'm using ... to split new array to multiply pairs (after map it looks like [{'cardType':'iDEBIT'}, ... ]). So in the end, new {} receives every key:property from each pair from mapped array.

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

How do I display a text file content in CMD?

To do this, you can use Microsoft's more advanced command-line shell called "Windows PowerShell." It should come standard on the latest versions of Windows, but you can download it from Microsoft if you don't already have it installed.

To get the last five lines in the text file simply read the file using Get-Content, then have Select-Object pick out the last five items/lines for you:

Get-Content c:\scripts\test.txt | Select-Object -last 5

Source: Using the Get-Content Cmdlet

How set background drawable programmatically in Android

Inside the app/res/your_xml_layout_file.xml

  1. Assign a name to your parent layout.
  2. Go to your MainActivity and find your RelativeLayout by calling the findViewById(R.id."given_name").
  3. Use the layout as a classic Object, by calling the method setBackgroundColor().

How can I add to a List's first position?

Use Insert method: list.Insert(0, item);

input file appears to be a text format dump. Please use psql

In order to create a backup using pg_dump that is compatible with pg_restore you must use the --format=custom / -Fc when creating your dump.

From the docs:

Output a custom-format archive suitable for input into pg_restore.

So your pg_dump command might look like:

pg_dump --file /tmp/db.dump --format=custom --host localhost --dbname my-source-database --username my-username --password

And your pg_restore command:

pg_restore --verbose --clean --no-acl --no-owner --host localhost --dbname my-destination-database /tmp/db.dump

Forcing to download a file using PHP

A previous answer on this page describes how to use .htaccess to force all files of a certain type to download. However, the solution does not work with all file types across all browsers. This is a more reliable way:

<FilesMatch "\.(?i:csv)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

You might need to flush your browser cache to see this working correctly.

Strip out HTML and Special Characters

You can do it in one single line :) specially useful for GET or POST requests

$clear = preg_replace('/[^A-Za-z0-9\-]/', '', urldecode($_GET['id']));

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

Convert java.time.LocalDate into java.util.Date type

You can use java.sql.Date.valueOf() method as:

Date date = java.sql.Date.valueOf(localDate);

No need to add time and time zone info here because they are taken implicitly.
See LocalDate to java.util.Date and vice versa simpliest conversion?

Eclipse does not start when I run the exe?

Reinstalling eclipse (newer version) did the trick for me.

HTML form with two submit buttons and two "target" attributes

Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.

<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>

Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not

function v(){
var check = document.getElementsByTagName("input");

    for (var i=0; i < check.length; i++) {
        if (check[i].type == 'checkbox') {
            if (check[i].checked == true) {

        x[i]=check[i].value
            }
        }
    }
console.log(x);
}   

run a python script in terminal without the python command

You need to use a hashbang. Add it to the first line of your python script.

#! <full path of python interpreter>

Then change the file permissions, and add the executing permission.

chmod +x <filename>

And finally execute it using

./<filename>

If its in the current directory,

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

With bash 4.2 and newer you can use something like this to strip the trailing CR, which only uses bash built-ins:

if [[ "${str: -1}" == $'\r' ]]; then
    str="${str:: -1}"
fi

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

Spring MVC Multipart Request with JSON

This must work!

client (angular):

$scope.saveForm = function () {
      var formData = new FormData();
      var file = $scope.myFile;
      var json = $scope.myJson;
      formData.append("file", file);
      formData.append("ad",JSON.stringify(json));//important: convert to JSON!
      var req = {
        url: '/upload',
        method: 'POST',
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function (data, headersGetterFunction) {
          return data;
        }
      };

Backend-Spring Boot:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {

        Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd

How to print a double with two decimals in Android?

For Displaying digit upto two decimal places there are two possibilities - 1) Firstly, you only want to display decimal digits if it's there. For example - i) 12.10 to be displayed as 12.1, ii) 12.00 to be displayed as 12. Then use-

DecimalFormat formater = new DecimalFormat("#.##"); 

2) Secondly, you want to display decimal digits irrespective of decimal present For example -i) 12.10 to be displayed as 12.10. ii) 12 to be displayed as 12.00.Then use-

DecimalFormat formater = new DecimalFormat("0.00"); 

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

In this folder there are all emulator images. If you don't use emulator then you can delete this folder.

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

Find root build.gradle file and add google maven repo inside allprojects tag

repositories {
        mavenLocal()
        mavenCentral()
        maven {                                  // <-- Add this
            url 'https://maven.google.com/' 
            name 'Google'
        }
    } 

It's better to use specific version instead of variable version

compile 'com.android.support:appcompat-v7:27.0.0'

If you're using Android Plugin for Gradle 3.0.0 or latter version

repositories {
      mavenLocal()
      mavenCentral()
      google()        //---> Add this
} 

and inject dependency in this way :

implementation 'com.android.support:appcompat-v7:27.0.0'

how to merge 200 csv files in Python

A slight change to the code above as it does not actually work correctly.

It should be as follows...

from glob import glob

with open('main.csv', 'a') as singleFile:
    for csv in glob('*.csv'):
        if csv == 'main.csv':
            pass
        else:
            for line in open(csv, 'r'):
                singleFile.write(line)

How to delete columns in numpy.array

In your situation, you can extract the desired data with:

a[:, -z]

"-z" is the logical negation of the boolean array "z". This is the same as:

a[:, logical_not(z)]

Using sed, how do you print the first 'N' characters of a line?

Don't use sed, use cut:

grep .... | cut -c 1-N

If you MUST use sed:

grep ... | sed -e 's/^\(.\{12\}\).*/\1/'

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

On your new AppDomain, try setting an AssemblyResolve event handler. That event gets called when a dependency is missing.

How to let an ASMX file output JSON

Are you calling the web service from client script or on the server side?

You may find sending a content type header to the server will help, e.g.

'application/json; charset=utf-8'

On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.

What is the difference between typeof and instanceof and when should one be used vs. the other?

To be very precise instanceof should be used where value is created via the constructor (generally custom types) for e.g.

var d = new String("abc")

whereas typeof to check values created just by assignments for e.g

var d = "abc"

How to define a two-dimensional array?

Here is a shorter notation for initializing a list of lists:

matrix = [[0]*5 for i in range(5)]

Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:

>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]

Java: splitting the filename into a base and extension

Source: http://www.java2s.com/Code/Java/File-Input-Output/Getextensionpathandfilename.htm

such an utility class :

class Filename {
  private String fullPath;
  private char pathSeparator, extensionSeparator;

  public Filename(String str, char sep, char ext) {
    fullPath = str;
    pathSeparator = sep;
    extensionSeparator = ext;
  }

  public String extension() {
    int dot = fullPath.lastIndexOf(extensionSeparator);
    return fullPath.substring(dot + 1);
  }

  public String filename() { // gets filename without extension
    int dot = fullPath.lastIndexOf(extensionSeparator);
    int sep = fullPath.lastIndexOf(pathSeparator);
    return fullPath.substring(sep + 1, dot);
  }

  public String path() {
    int sep = fullPath.lastIndexOf(pathSeparator);
    return fullPath.substring(0, sep);
  }
}

usage:

public class FilenameDemo {
  public static void main(String[] args) {
    final String FPATH = "/home/mem/index.html";
    Filename myHomePage = new Filename(FPATH, '/', '.');
    System.out.println("Extension = " + myHomePage.extension());
    System.out.println("Filename = " + myHomePage.filename());
    System.out.println("Path = " + myHomePage.path());
  }
}

What is the "right" JSON date format?

"2014-01-01T23:28:56.782Z"

The date is represented in a standard and sortable format that represents a UTC time (indicated by the Z). ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset:

"2014-02-01T09:28:56.321-10:00"

There are other variations of the timezone encoding in the ISO 8601 spec, but the –10:00 format is the only TZ format that current JSON parsers support. In general it’s best to use the UTC based format (Z) unless you have a specific need for figuring out the time zone in which the date was produced (possible only in server side generation).

NB:

    var date = new Date();
    console.log(date); // Wed Jan 01 2014 13:28:56 GMT- 
    1000 (Hawaiian Standard Time) 
        
    var json = JSON.stringify(date);
    console.log(json);  // "2014-01-01T23:28:56.782Z"

To tell you that's the preferred way even though JavaScript doesn't have a standard format for it

// JSON encoded date
var json = "\"2014-01-01T23:28:56.782Z\"";

var dateStr = JSON.parse(json);  
console.log(dateStr); // 2014-01-01T23:28:56.782Z

What's the difference between a mock & stub?

Stub helps us to run test. How? It gives values which helps to run test. These values are itself not real and we created these values just to run the test. For example we create a HashMap to give us values which are similar to values in database table. So instead of directly interacting with database we interact with Hashmap.

Mock is an fake object which runs the test. where we put assert.

How to align iframe always in the center

I think if you add margin: auto; to the div below it should work.

div#iframe-wrapper iframe {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    right: 100px;
    height: 100%;
    width: 100%;
}

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                String header = dataGridView1.Columns[i].HeaderText;
                //String cellText = row.Cells[i].Text;
                DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column 
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
                int colWidth = column.Width; // store columns width after auto resize           
                colWidth += 50; // add 30 pixels to what 'colWidth' already is
                this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
            }
        }

WCF Service, the type provided as the service attribute values…could not be found

This is an old bug, but I encountered it today on a web service which had barely been altered since being created via "New \ Project.."

For me, this issue was caused by the "IService.cs" file containing the following:

<%@ ServiceHost Language="C#" Debug="true" Service="JSONWebService.Service1.svc" CodeBehind="Service1.svc.cs" %>

Notice the value in the Service attribute contains ".svc" at the end.

This shouldn't be there.

Removing those 4 characters resolved this issue.

<%@ ServiceHost Language="C#" Debug="true" Service="JSONWebService.Service1" CodeBehind="Service1.svc.cs" %>

Note that you need to open this file from outside of Visual Studio.

Visual Studio shows one file, Service1.cs in the Solution Explorer, but that only lets you alter Service1.svc.cs, not the Service1.svc file.

How can I call a function using a function pointer?

The best way to read that is the clockwise/spiral rule by David Anderson.

Getting the screen resolution using PHP

PHP is a server side language - it's executed on the server only, and the resultant program output is sent to the client. As such, there's no "client screen" information available.

That said, you can have the client tell you what their screen resolution is via JavaScript. Write a small scriptlet to send you screen.width and screen.height - possibly via AJAX, or more likely with an initial "jump page" that finds it, then redirects to http://example.net/index.php?size=AxB

Though speaking as a user, I'd much prefer you to design a site to fluidly handle any screen resolution. I browse in different sized windows, mostly not maximized.

Initial bytes incorrect after Java AES/CBC decryption

Another solution using java.util.Base64 with Spring Boot

Encryptor Class

package com.jmendoza.springboot.crypto.cipher;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Component
public class Encryptor {

    @Value("${security.encryptor.key}")
    private byte[] key;
    @Value("${security.encryptor.algorithm}")
    private String algorithm;

    public String encrypt(String plainText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return new String(Base64.getEncoder().encode(cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8))));
    }

    public String decrypt(String cipherText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)));
    }
}

EncryptorController Class

package com.jmendoza.springboot.crypto.controller;

import com.jmendoza.springboot.crypto.cipher.Encryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cipher")
public class EncryptorController {

    @Autowired
    Encryptor encryptor;

    @GetMapping(value = "encrypt/{value}")
    public String encrypt(@PathVariable("value") final String value) throws Exception {
        return encryptor.encrypt(value);
    }

    @GetMapping(value = "decrypt/{value}")
    public String decrypt(@PathVariable("value") final String value) throws Exception {
        return encryptor.decrypt(value);
    }
}

application.properties

server.port=8082
security.encryptor.algorithm=AES
security.encryptor.key=M8jFt46dfJMaiJA0

Example

http://localhost:8082/cipher/encrypt/jmendoza

2h41HH8Shzc4BRU3hVDOXA==

http://localhost:8082/cipher/decrypt/2h41HH8Shzc4BRU3hVDOXA==

jmendoza

Check for file exists or not in sql server?

You can achieve this using a cursor but the performance is much slower than whileloop.. Here's the code:

set nocount on
declare cur cursor local fast_forward for
    (select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;

fetch from cur into @fullpath
while @@FETCH_STATUS = 0
    begin
        exec xp_fileexist @fullpath, @isExists out
        if @isExists = 1            
            print @fullpath + char(9) + char(9) + 'file exists'
        else            
            print @fullpath + char(9) + char(9) + 'file does not exists'
        fetch from cur into @fullpath
    end
close cur
deallocate cur

or you can put it in a tempTable if you want to integrate it in your frontend..

create proc GetFileStatus as
begin
    set nocount on
    create table #tempFileStatus(FilePath varchar(300),FileStatus varchar(30))
    declare cur cursor local fast_forward for
        (select filepath from Directory)
    open cur;
    declare @fullpath varchar(250);
    declare @isExists int;

    fetch from cur into @fullpath
    while @@FETCH_STATUS = 0
        begin
            exec xp_fileexist @fullpath, @isExists out
            if @isExists = 1                
                insert into #tempFileStatus values(@fullpath,'File exist')
            else
                insert into #tempFileStatus values(@fullpath,'File does not exists')
            fetch from cur into @fullpath
        end
    close cur
    deallocate cur
    select * from #tempFileStatus
    drop table #tempFileStatus
end

then call it using:

exec GetFileStatus

How can I start InternetExplorerDriver using Selenium WebDriver

To run test cases in IE Browser make sure you have downloaded IE driver and you need to set the property as well.

Below code will help you

// This will set the driver
System.setProperty("webdriver.ie.driver","driver path\\IEDriverServer.exe");

// Initialise browser

WebDriver driver=new InternetExplorerDriver();

You can check IE Browser challenges with Selenium and complete code for more details

How do I rotate the Android emulator display?

Press Left Ctrl + F11 or Left Ctrl + F12 to rotate the emulator view.

Note: Right Ctrl doesn't work;

Difference between abstract class and interface in Python

In a more basic way to explain: An interface is sort of like an empty muffin pan. It's a class file with a set of method definitions that have no code.

An abstract class is the same thing, but not all functions need to be empty. Some can have code. It's not strictly empty.

Why differentiate: There's not much practical difference in Python, but on the planning level for a large project, it could be more common to talk about interfaces, since there's no code. Especially if you're working with Java programmers who are accustomed to the term.

How to give ASP.NET access to a private key in a certificate in the certificate store?

If you are trying to load a cert from a .pfx file in IIS the solution may be as simple as enabling this option for the Application Pool.

Right click on the App Pool and select Advanced Settings.

Then enable Load User Profile


enter image description here

How to install Visual C++ Build tools?

The current version (2019/03/07) is Build Tools for Visual Studio 2017. It's an online installer, you need to include at least the individual components:

  • VC++ 2017 version xx.x tools
  • Windows SDK to use standard libraries.

UTL_FILE.FOPEN() procedure not accepting path for directory?

Don't forget also that the path for the file is on the actual oracle server machine and not any local development machine that might be calling your stored procedure. This is probably very obvious but something that should be remembered.

Memory errors and list limits?

The MemoryError exception that you are seeing is the direct result of running out of available RAM. This could be caused by either the 2GB per program limit imposed by Windows (32bit programs), or lack of available RAM on your computer. (This link is to a previous question).

You should be able to extend the 2GB by using 64bit copy of Python, provided you are using a 64bit copy of windows.

The IndexError would be caused because Python hit the MemoryError exception before calculating the entire array. Again this is a memory issue.

To get around this problem you could try to use a 64bit copy of Python or better still find a way to write you results to file. To this end look at numpy's memory mapped arrays.

You should be able to run you entire set of calculation into one of these arrays as the actual data will be written disk, and only a small portion of it held in memory.

jQuery - how can I find the element with a certain id?

This is one more option to find the element for above question

$("#tbIntervalos").find('td[id="'+horaInicial+'"]')

Checking version of angular-cli that's installed?

In Command line we can check our installed ng version.

ng -v OR ng --version OR ng version

This will give you like this :

 _                      _                 ____ _     ___

   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/

Angular CLI: 1.6.5
Node: 8.0.0
OS: linux x64
Angular: 
...

How to convert .pem into .key?

I assume you want the DER encoded version of your PEM private key.

openssl rsa -outform der -in private.pem -out private.key

How to execute a bash command stored as a string with quotes and asterisk

Have you tried:

eval $cmd

For the follow-on question of how to escape * since it has special meaning when it's naked or in double quoted strings: use single quotes.

MYSQL='mysql AMORE -u username -ppassword -h localhost -e'
QUERY="SELECT "'*'" FROM amoreconfig" ;# <-- "double"'single'"double"
eval $MYSQL "'$QUERY'"

Bonus: It also reads nice: eval mysql query ;-)

How to get the difference between two arrays in JavaScript?

This is by far the easiest way to get exactly the result you are looking for, using jQuery:

var diff = $(old_array).not(new_array).get();

diff now contains what was in old_array that is not in new_array

How do I automatically resize an image for a mobile site?

You can use the following css to resize the image for mobile view

object-fit: scale-down; max-width: 100%

How can I pair socks from a pile efficiently?

Sorting solutions have been proposed, but sorting is a little too much: We don't need order; we just need equality groups.

So hashing would be enough (and faster).

  1. For each color of socks, form a pile. Iterate over all socks in your input basket and distribute them onto the color piles.
  2. Iterate over each pile and distribute it by some other metric (e.g. pattern) into the second set of piles
  3. Recursively apply this scheme until you have distributed all socks onto very small piles that you can visually process immediately

This kind of recursive hash partitioning is actually being done by SQL Server when it needs to hash join or hash aggregate over huge data sets. It distributes its build input stream into many partitions which are independent. This scheme scales to arbitrary amounts of data and multiple CPUs linearly.

You don't need recursive partitioning if you can find a distribution key (hash key) that provides enough buckets that each bucket is small enough to be processed very quickly. Unfortunately, I don't think socks have such a property.

If each sock had an integer called "PairID" one could easily distribute them into 10 buckets according to PairID % 10 (the last digit).

The best real-world partitioning I can think of is creating a rectangle of piles: one dimension is color, the other is the pattern. Why a rectangle? Because we need O(1) random-access to piles. (A 3D cuboid would also work, but that is not very practical.)


Update:

What about parallelism? Can multiple humans match the socks faster?

  1. The simplest parallelization strategy is to have multiple workers take from the input basket and put the socks onto the piles. This only scales up so much - imagine 100 people fighting over 10 piles. The synchronization costs (manifesting themselves as hand-collisions and human communication) destroy efficiency and speed-up (see the Universal Scalability Law!). Is this prone to deadlocks? No, because each worker only needs to access one pile at a time. With just one "lock" there cannot be a deadlock. Livelocks might be possible depending on how the humans coordinate access to piles. They might just use random backoff like network cards do that on a physical level to determine what card can exclusively access the network wire. If it works for NICs, it should work for humans as well.
  2. It scales nearly indefinitely if each worker has its own set of piles. Workers can then take big chunks of socks from the input basket (very little contention as they are doing it rarely) and they do not need to synchronise when distributing the socks at all (because they have thread-local piles). At the end, all workers need to union their pile-sets. I believe that can be done in O(log (worker count * piles per worker)) if the workers form an aggregation tree.

What about the element distinctness problem? As the article states, the element distinctness problem can be solved in O(N). This is the same for the socks problem (also O(N), if you need only one distribution step (I proposed multiple steps only because humans are bad at calculations - one step is enough if you distribute on md5(color, length, pattern, ...), i.e. a perfect hash of all attributes)).

Clearly, one cannot go faster than O(N), so we have reached the optimal lower bound.

Although the outputs are not exactly the same (in one case, just a boolean. In the other case, the pairs of socks), the asymptotic complexities are the same.

SQL Server 2008: How to query all databases sizes?

All this examples work fine on most of my database servers. However if you have 1 server with multiple instances and all those servers those query's give you no result.

For instance the first query gives a result like:

name    DataFileSizeMB  LogFileSizeMB
master  NULL    NULL
tempdb  NULL    NULL
model   NULL    NULL
msdb    NULL    NULL

So the databases are selected from sys.databases, however the table sys.master_files seems to be empty or gives no result.

Even a simple query as select * from sys.master_files has a result of 0 records. You don't receive any errors but no records are found. On my servers with only 1 database instance this works fine.

What is a quick way to force CRLF in C# / .NET?

Simple variant:

Regex.Replace(input, @"\r\n|\r|\n", "\r\n")

For better performance:

static Regex newline_pattern = new Regex(@"\r\n|\r|\n", RegexOptions.Compiled);
[...]
    newline_pattern.Replace(input, "\r\n");

What is the difference between C# and .NET?

C# is a programming language, .NET is a blanket term that tends to cover both the .NET Framework (an application framework library) and the Common Language Runtime which is the runtime in which .NET assemblies are run.

Microsoft's implementation of C# is heavily integrated with the .NET Framework so it is understandable that the two concepts would be confused. However it is important to understand that they are two very different things.

Here is a class written in C#:

class Example { }

Here is a class written in C# that explicitly uses a .NET framework assembly, type, and method:

class Example
{
    static void Main()
    {
        // Here we call into the .NET framework to 
        // write to the output console
        System.Console.Write("hello, world");
    }
}

As I mentioned before, it is very difficult to use Microsoft's implementation of C# without using the .NET framework as well. My first Example implementation above even uses the .NET framework (implicitly, yes, but it does use it nonetheless) because Example inherits from System.Object.

Also, the reason I use the phrase Microsoft's implementation of C# is because there are other implementations of C# available.

How can I install an older version of a package via NuGet?

Now, it's very much simplified in Visual Studio 2015 and later. You can do downgrade / upgrade within the User interface itself, without executing commands in the Package Manager Console.

  1. Right click on your project and *go to Manage NuGet Packages.

  2. Look at the below image.

    • Select your Package and Choose the Version, which you wanted to install.

NuGet Package Manager window of Project

Very very simple, isn't it? :)

How do I format a date in VBA with an abbreviated month?

I'm using

Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"

to format a column

So I guess

Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"

would do the trick for you.

More: NumberFormat function.

How to get the current loop index when using Iterator?

Use a ListIterator to iterate through the Collection. If the Collection is not a List to start with use Arrays.asList(Collection.toArray()) to turn it into a List first.

I can't install python-ldap

If you're working with windows machines, you can find 'python-ldap' wheel in this Link and then you can install it

Python Sets vs Lists

Set wins due to near instant 'contains' checks: https://en.wikipedia.org/wiki/Hash_table

List implementation: usually an array, low level close to the metal good for iteration and random access by element index.

Set implementation: https://en.wikipedia.org/wiki/Hash_table, it does not iterate on a list, but finds the element by computing a hash from the key, so it depends on the nature of the key elements and the hash function. Similar to what is used for dict. I suspect list could be faster if you have very few elements (< 5), the larger element count the better the set will perform for a contains check. It is also fast for element addition and removal. Also always keep in mind that building a set has a cost !

NOTE: If the list is already sorted, searching the list could be quite fast on small lists, but with more data a set is faster for contains checks.

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.

If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.

  • To show the wait_timeout value:

SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+

| Variable_name | Value |

+---------------+-------+

| wait_timeout | 28800 |

+---------------+-------+

the value is in second, it means that non-interactive connection still up to 8 hours.

  • To change the value of "wait_timeout" variable:

SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)

After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.

Split pandas dataframe in two if it has more than 10 rows

This will return the split DataFrames if the condition is met, otherwise return the original and None (which you would then need to handle separately). Note that this assumes the splitting only has to happen one time per df and that the second part of the split (if it is longer than 10 rows (meaning that the original was longer than 20 rows)) is OK.

df_new1, df_new2 = df[:10, :], df[10:, :] if len(df) > 10 else df, None

Note you can also use df.head(10) and df.tail(len(df) - 10) to get the front and back according to your needs. You can also use various indexing approaches: you can just provide the first dimensions index if you want, such as df[:10] instead of df[:10, :] (though I like to code explicitly about the dimensions you are taking). You can can also use df.iloc and df.ix to index in similar ways.

Be careful about using df.loc however, since it is label-based and the input will never be interpreted as an integer position. .loc would only work "accidentally" in the case when you happen to have index labels that are integers starting at 0 with no gaps.

But you should also consider the various options that pandas provides for dumping the contents of the DataFrame into HTML and possibly also LaTeX to make better designed tables for the presentation (instead of just copying and pasting). Simply Googling how to convert the DataFrame to these formats turns up lots of tutorials and advice for exactly this application.

What is the difference between fastcgi and fpm?

What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

How to compare strings in an "if" statement?

You can't compare array of characters using == operator. You have to use string compare functions. Take a look at Strings (c-faq).

The standard library's strcmp function compares two strings, and returns 0 if they are identical, or a negative number if the first string is alphabetically "less than" the second string, or a positive number if the first string is "greater."

TypeError: 'dict' object is not callable

You need to use:

number_map[int(x)]

Note the square brackets!

Quicker way to get all unique values of a column in VBA?

Use Excel's AdvancedFilter function to do this.

Using Excels inbuilt C++ is the fastest way with smaller datasets, using the dictionary is faster for larger datasets. For example:

Copy values in Column A and insert the unique values in column B:

Range("A1:A6").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("B1"), Unique:=True

It works with multiple columns too:

Range("A1:B4").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("D1:E1"), Unique:=True

Be careful with multiple columns as it doesn't always work as expected. In those cases I resort to removing duplicates which works by choosing a selection of columns to base uniqueness. Ref: MSDN - Find and remove duplicates

enter image description here

Here I remove duplicate columns based on the third column:

Range("A1:C4").RemoveDuplicates Columns:=3, Header:=xlNo

Here I remove duplicate columns based on the second and third column:

Range("A1:C4").RemoveDuplicates Columns:=Array(2, 3), Header:=xlNo

How to checkout a specific Subversion revision from the command line?

You could try

TortoiseProc.exe /command:checkout /rev:1234

to get revision 1234.

I'm not 100% sure the /rev option is compatible with checkout, but I got the idea from some TortoiseProc documentation.

How do I programmatically force an onchange event on an input?

if you're using jQuery you would have:

$('#elementId').change(function() { alert('Do Stuff'); });

or MS AJAX:

$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });

Or in the raw HTML of the element:

<input type="text" onchange="alert('Do Stuff');" id="myElement" />

After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:

$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
  alert('Do Stuff!');
}
function editElement(){
  var el = $get('elementId');
  el.value = 'something new';
  elementChanged();
}

Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.

Or, if you are using the Microsoft AJAX framework you can access all the event handlers via:

$get('elementId')._events

It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.

Where in an Eclipse workspace is the list of projects stored?

In Linux after deleting

<workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\

Does not worked.

After that i have done File->Refresh

Then it cleared all old project listed from eclipse.

How do I keep Python print from adding newlines or spaces?

Or use a +, i.e.:

>>> print 'me'+'no'+'likee'+'spacees'+'pls'
menolikeespaceespls

Just make sure all are concatenate-able objects.

How to enable C++11 in Qt Creator?

If you are using an earlier version of QT (<5) try this

QMAKE_CXXFLAGS += -std=c++0x

How do you launch the JavaScript debugger in Google Chrome?

The most efficient way I have found to get to the javascript debugger is by running this:

chrome://inspect

Removing display of row names from data frame

If you want to format your table via kable, you can use row.names = F

kable(df, row.names = F)

How to switch between frames in Selenium WebDriver using Java

First you have to locate the frame id and define it in a WebElement

For ex:- WebElement fr = driver.findElementById("id");

Then switch to the frame using this code:- driver.switchTo().frame("Frame_ID");

An example script:-

WebElement fr = driver.findElementById("theIframe");

driver.switchTo().frame(fr);

Then to move out of frame use:- driver.switchTo().defaultContent();

R: Break for loop

Well, your code is not reproducible so we will never know for sure, but this is what help('break')says:

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.

So yes, break only breaks the current loop. You can also see it in action with e.g.:

for (i in 1:10)
{
    for (j in 1:10)
    {
        for (k in 1:10)
        {
            cat(i," ",j," ",k,"\n")
            if (k ==5) break
        }   
    }
}

How to sort by Date with DataTables jquery plugin?

Date Sort - with a hidden element

Convert the date to the format YYYYMMDD and prepend to the actual value (MM/DD/YYYY) in the <td>, wrap it in an element, set style display:none; to the elements. Now the date sort will work as a normal sort. The same can be applied to date-time sort.

HTML

<table id="data-table">
   <tr>
     <td><span>YYYYMMDD</span>MM/DD/YYYY</td>
   </tr>
</table>

CSS

#data-table span {
    display:none; 
}

How do Python functions handle the types of the parameters that you pass in?

Many languages have variables, which are of a specific type and have a value. Python does not have variables; it has objects, and you use names to refer to these objects.

In other languages, when you say:

a = 1

then a (typically integer) variable changes its contents to the value 1.

In Python,

a = 1

means “use the name a to refer to the object 1”. You can do the following in an interactive Python session:

>>> type(1)
<type 'int'>

The function type is called with the object 1; since every object knows its type, it's easy for type to find out said type and return it.

Likewise, whenever you define a function

def funcname(param1, param2):

the function receives two objects, and names them param1 and param2, regardless of their types. If you want to make sure the objects received are of a specific type, code your function as if they are of the needed type(s) and catch the exceptions that are thrown if they aren't. The exceptions thrown are typically TypeError (you used an invalid operation) and AttributeError (you tried to access an inexistent member (methods are members too) ).

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

You can use this extensions to improve substringWithRange

Swift 2.3

extension String
{   
    func substringWithRange(start: Int, end: Int) -> String
    {
        if (start < 0 || start > self.characters.count)
        {
            print("start index \(start) out of bounds")
            return ""
        }
        else if end < 0 || end > self.characters.count
        {
            print("end index \(end) out of bounds")
            return ""
        }
        let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(end))
        return self.substringWithRange(range)
    }

    func substringWithRange(start: Int, location: Int) -> String
    {
        if (start < 0 || start > self.characters.count)
        {
            print("start index \(start) out of bounds")
            return ""
        }
        else if location < 0 || start + location > self.characters.count
        {
            print("end index \(start + location) out of bounds")
            return ""
        }
        let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(start + location))
        return self.substringWithRange(range)
    }
}

Swift 3

extension String
{
    func substring(start: Int, end: Int) -> String
    {
        if (start < 0 || start > self.characters.count)
        {
            print("start index \(start) out of bounds")
            return ""
        }
        else if end < 0 || end > self.characters.count
        {
            print("end index \(end) out of bounds")
            return ""
        }
        let startIndex = self.characters.index(self.startIndex, offsetBy: start)
        let endIndex = self.characters.index(self.startIndex, offsetBy: end)
        let range = startIndex..<endIndex

        return self.substring(with: range)
    }

    func substring(start: Int, location: Int) -> String
    {
        if (start < 0 || start > self.characters.count)
        {
            print("start index \(start) out of bounds")
            return ""
        }
        else if location < 0 || start + location > self.characters.count
        {
            print("end index \(start + location) out of bounds")
            return ""
        }
        let startIndex = self.characters.index(self.startIndex, offsetBy: start)
        let endIndex = self.characters.index(self.startIndex, offsetBy: start + location)
        let range = startIndex..<endIndex

        return self.substring(with: range)
    }
}

Usage:

let str = "Hello, playground"

let substring1 = str.substringWithRange(0, end: 5) //Hello
let substring2 = str.substringWithRange(7, location: 10) //playground

Installing Python library from WHL file

First open a console then cd to where you've downloaded your file like some-package.whl and use

pip install some-package.whl

Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. I have multiple Python installations, and needed to use the pip associated with Python 3 to install a version 3 wheel.

If pip is not installed, and you are using Windows: How to install pip on Windows?

Detecting the character encoding of an HTTP POST request

Try setting the charset on your Content-Type:

httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );

Auto increment in phpmyadmin

This is due to the wp_terms, wp_termmeta and wp_term_taxonomy tables, which had all their ID's not set to AUTO_INCREMENT

To do this go to phpmyadmin, click on the concern database, wp_terms table, click on structure Tab, at right side you will see a tab named A_I(AUTO_INCREMENT), check it and save (You are only doing this for the first option, in the case wp_term you are only doing it for term_id).

Do the same for wp_termmeta and wp_term_taxonomy that will fix the issue.

Is there a way to disable initial sorting for jquery DataTables?

Well I found the answer set "aaSorting" to an empty array:

$(document).ready( function() {
    $('#example').dataTable({
        /* Disable initial sort */
        "aaSorting": []
    });
})

For newer versions of Datatables (>= 1.10) use order option:

$(document).ready( function() {
    $('#example').dataTable({
        /* No ordering applied by DataTables during initialisation */
        "order": []
    });
})

Java Try Catch Finally blocks without Catch

Inside try block we write codes that can throw an exception. The catch block is where we handle the exception. The finally block is always executed no matter whether exception occurs or not.

Now if we have try-finally block instead of try-catch-finally block then the exception will not be handled and after the try block instead of control going to catch block it will go to finally block. We can use try-finally block when we want to do nothing with the exception.

HtmlEncode from Class Library

Add a reference to System.Web.dll and then you can use the System.Web.HtmlUtility class

TypeError: 'NoneType' object is not iterable in Python

It means that the data variable is passing None (which is type NoneType), its equivalent for nothing. So it can't be iterable as a list, as you are trying to do.

How can I declare and define multiple variables in one line using C++?

When you declare a variable without initializing it, a random number from memory is selected and the variable is initialized to that value.

TypeError: Router.use() requires middleware function but got a Object

If your are using express above 2.x, you have to declare app.router like below code. Please try to replace your code

app.use('/', routes);

with

app.use(app.router);
routes.initialize(app);

Please click here to get more details about app.router

Note:

app.router is depreciated in express 3.0+. If you are using express 3.0+, refer to Anirudh's answer below.

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Parsing date string in Go

If you have worked with time/date formatting/parsing in other languages you might have noticed that the other languages use special placeholders for time/date formatting. For eg ruby language uses

%d for day
%Y for year

etc. Golang, instead of using codes such as above, uses date and time format placeholders that look like date and time only. Go uses standard time, which is:

Mon Jan 2 15:04:05 MST 2006  (MST is GMT-0700)
or 
01/02 03:04:05PM '06 -0700

So if you notice Go uses

01 for the day of the month,
02 for the month
03 for hours,
04 for minutes
05 for second
and so on

Therefore for example for parsing 2020-01-29, layout string should be 06-01-02 or 2006-01-02.

You can refer to the full placeholder layout table at this link - https://golangbyexample.com/parse-time-in-golang/

The difference between sys.stdout.write and print?

print is just a thin wrapper that formats the inputs (modifiable, but by default with a space between args and newline at the end) and calls the write function of a given object. By default this object is sys.stdout, but you can pass a file using the "chevron" form. For example:

print >> open('file.txt', 'w'), 'Hello', 'World', 2+3

See: https://docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement


In Python 3.x, print becomes a function, but it is still possible to pass something other than sys.stdout thanks to the fileargument.

print('Hello', 'World', 2+3, file=open('file.txt', 'w'))

See https://docs.python.org/3/library/functions.html#print


In Python 2.6+, print is still a statement, but it can be used as a function with

from __future__ import print_function

Update: Bakuriu commented to point out that there is a small difference between the print function and the print statement (and more generally between a function and a statement).

In case of an error when evaluating arguments:

print "something", 1/0, "other" #prints only something because 1/0 raise an Exception

print("something", 1/0, "other") #doesn't print anything. The function is not called

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

How to upload image in CodeIgniter?

Simple Image upload in codeigniter

Find below code for easy image upload

public function doupload()
     {
        $upload_path="https://localhost/project/profile"  
        $uid='10'; //creare seperate folder for each user 
        $upPath=upload_path."/".$uid;
        if(!file_exists($upPath)) 
        {
                   mkdir($upPath, 0777, true);
        }
        $config = array(
        'upload_path' => $upPath,
        'allowed_types' => "gif|jpg|png|jpeg",
        'overwrite' => TRUE,
        'max_size' => "2048000", 
        'max_height' => "768",
        'max_width' => "1024"
        );
        $this->load->library('upload', $config);
        if(!$this->upload->do_upload('userpic'))
        { 
            $data['imageError'] =  $this->upload->display_errors();

        }
        else
        {
            $imageDetailArray = $this->upload->data();
            $image =  $imageDetailArray['file_name'];
        }

     }

Hope this helps you to upload image

When to use static methods

There are some valid reasons to use static methods:

  • Performance: if you want some code to be run, and don't want to instantiate an extra object to do so, shove it into a static method. The JVM also can optimize static methods a lot (I think I've once read James Gosling declaring that you don't need custom instructions in the JVM, since static methods will be just as fast, but couldn't find the source - thus it could be completely false). Yes, it is micro-optimization, and probably unneeded. And we programmers never do unneeded things just because they are cool, right?

  • Practicality: instead of calling new Util().method(arg), call Util.method(arg), or method(arg) with static imports. Easier, shorter.

  • Adding methods: you really wanted the class String to have a removeSpecialChars() instance method, but it's not there (and it shouldn't, since your project's special characters may be different from the other project's), and you can't add it (since Java is somewhat sane), so you create an utility class, and call removeSpecialChars(s) instead of s.removeSpecialChars(). Sweet.

  • Purity: taking some precautions, your static method will be a pure function, that is, the only thing it depends on is its parameters. Data in, data out. This is easier to read and debug, since you don't have inheritance quirks to worry about. You can do it with instance methods too, but the compiler will help you a little more with static methods (by not allowing references to instance attributes, overriding methods, etc.).

You'll also have to create a static method if you want to make a singleton, but... don't. I mean, think twice.

Now, more importantly, why you wouldn't want to create a static method? Basically, polymorphism goes out of the window. You'll not be able to override the method, nor declare it in an interface (pre-Java 8). It takes a lot of flexibility out from your design. Also, if you need state, you'll end up with lots of concurrency bugs and/or bottlenecks if you are not careful.

How do I open a new window using jQuery?

Those are by no means the same. The first will simply send you to whatever URL you have assigned to window.location.href (in the same window you're currently in). The second makes a GET AJAX request.

Try this page: http://www.codebelt.com/jquery/open-new-browser-window-with-jquery-custom-size/

It gives a great example on how to open a new window*.

If you wish to use raw javascript then this is what you're looking for:

window.open(URL,name,specs,replace)

As seen in http://www.w3schools.com/jsref/met_win_open.asp

Python matplotlib multiple bars

I know that this is about matplotlib, but using pandas and seaborn can save you a lot of time:

df = pd.DataFrame(zip(x*3, ["y"]*3+["z"]*3+["k"]*3, y+z+k), columns=["time", "kind", "data"])
plt.figure(figsize=(10, 6))
sns.barplot(x="time", hue="kind", y="data", data=df)
plt.show()

enter image description here

How do I set up cron to run a file just once at a specific time?

Try this out to execute a command on 30th March 2011 at midnight:

0 0 30 3 ? 2011  /command

WARNING: As noted in comments, the year column is not supported in standard/default implementations of cron. Please refer to TomOnTime answer below, for a proper way to run a script at a specific time in the future in standard implementations of cron.

How do you use variables in a simple PostgreSQL script?

Here's an example of using a variable in plpgsql:

create table test (id int);
insert into test values (1);
insert into test values (2);
insert into test values (3);

create function test_fn() returns int as $$
    declare val int := 2;
    begin
        return (SELECT id FROM test WHERE id = val);
    end;
$$ LANGUAGE plpgsql;

SELECT * FROM test_fn();
 test_fn 
---------
       2

Have a look at the plpgsql docs for more information.