Programs & Examples On #Errorplacement

Jquery Validate custom error message location

This Worked for me

Actually error is a array which contain error message and other values for elements we pass, you can console.log(error); and see. Inside if condition "error.appendTo($(element).parents('div').find($('.errorEmail')));" Is nothing but finding html element in code and passing the error message.

    $("form[name='contactUs']").validate({
rules: {
    message: 'required',
    name: "required",
    phone_number: {
        required: true,
        minlength: 10,
        maxlength: 10,
        number: false
    },
    email: {
        required: true,
        email: true
    }
},
messages: {
    name: "Please enter your name",
    email: "Please enter a valid email address",
    message: "Please enter your message",
    phone_number: "Please enter a valid mobile number"
},
errorPlacement: function(error, element) {
        $("#errorText").empty();

        if(error[0].htmlFor == 'name')
        {
            error.appendTo($(element).parents('div').find($('.errorName')));
        }
        if(error[0].htmlFor == 'email')
        {
            error.appendTo($(element).parents('div').find($('.errorEmail')));
        }
        if(error[0].htmlFor == 'phone_number')
        {
            error.appendTo($(element).parents('div').find($('.errorMobile')));
        }
        if(error[0].htmlFor == 'message')
        {
            error.appendTo($(element).parents('div').find($('.errorMessage')));
        }
      }
    });

Select folder dialog WPF

Only such dialog is FileDialog. Its part of WinForms, but its actually only wrapper around WinAPI standard OS file dialog. And I don't think it is ugly, its actually part of OS, so it looks like OS it is run on.

Other way, there is nothing to help you with. You either need to look for 3rd party implementation, either free (and I don't think there are any good) or paid.

Element-wise addition of 2 lists?

  • The zip function is useful here, used with a list comprehension v1, v2.
  • If you have a list of lists (instead of just two lists) you can use v3.
  • For lists with different length (for example: By adding 1 to the end of the first/secound list), then you can try something like this (using zip_longest) - v4
first = [1, 2, 3, 1]
second = [4, 5, 6]

output: [5, 7, 9, 1]
  • If you have an unknown number of lists of the same length, you can use the function v5.

  • v6 - The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y.

  • v7 - Assuming both lists first and second have same length, you do not need zip or anything else.

################
first = [1, 2, 3]
second = [4, 5, 6]

####### v1 ########
third1 = [sum(i) for i in zip(first,second)]

####### v2 ########
third2 = [x + y for x, y in zip(first, second)]

####### v3 ########
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
third3 = [sum(x) for x in zip(*lists_of_lists)]

####### v4 ########
from itertools import zip_longest
third4 = list(map(sum, zip_longest(first, second, fillvalue=0)))

####### v5 ########
def sum_lists(*args):
    return list(map(sum, zip(*args)))

third5 = sum_lists(first, second)

####### v6 ########
import operator
third6 = list(map(operator.add, first,second))

####### v7 ########
third7 =[first[i]+second[i] for i in range(len(first))]

####### v(i) ########

print(third1) # [5, 7, 9]
print(third2) # [5, 7, 9]
print(third3) # [5, 7, 9]
print(third4) # [5, 7, 9]
print(third5) # [5, 7, 9]
print(third6) # [5, 7, 9]
print(third7) # [5, 7, 9]

Get content of a cell given the row and column numbers

Try =index(ARRAY, ROW, COLUMN)

where: Array: select the whole sheet Row, Column: Your row and column references

That should be easier to understand to those looking at the formula.

Join two data frames, select all columns from one and some columns from the other

I got an error: 'a not found' using the suggested code:

from pyspark.sql.functions import col df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])

I changed a.columns to df1.columns and it worked out.

Difference between clustered and nonclustered index

faster to read than non cluster as data is physically storted in index order we can create only one per table.(cluster index)

quicker for insert and update operation than a cluster index. we can create n number of non cluster index.

Disabling SSL Certificate Validation in Spring RestTemplate

Essentially two things you need to do are use a custom TrustStrategy that trusts all certs, and also use NoopHostnameVerifier() to disable hostname verification. Here is the code, with all the relevant imports:

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public RestTemplate getRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return true;
        }
    };
    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;
}

Is there a better alternative than this to 'switch on type'?

You can create overloaded methods:

void Foo(A a) 
{ 
    a.Hop(); 
}

void Foo(B b) 
{ 
    b.Skip(); 
}

void Foo(object o) 
{ 
    throw new ArgumentException("Unexpected type: " + o.GetType()); 
}

And cast the argument to dynamic type in order to bypass static type checking:

Foo((dynamic)something);

How to install both Python 2.x and Python 3.x in Windows

I did this in three steps by following the instructions here: This is all taken directly from here: http://ipython.readthedocs.io/en/stable/install/kernel_install.html. I'm currently running Python 2.x on Windows 8 and have Anaconda 4.2.13 installed.

1) First install the latest version of python:

conda create -n python3 python=3 ipykernel

2) Next activate python3

activate python3

3) Install the kernel:

python -m ipykernel install --user

If you have Python 3 installed and want to install 2, switch the 2 and the 3 above. When you open a new notebook, you can now choose between Python 2 or 3.

How can I get the SQL of a PreparedStatement?

It's nowhere definied in the JDBC API contract, but if you're lucky, the JDBC driver in question may return the complete SQL by just calling PreparedStatement#toString(). I.e.

System.out.println(preparedStatement);

At least MySQL 5.x and PostgreSQL 8.x JDBC drivers support it. However, most other JDBC drivers doesn't support it. If you have such one, then your best bet is using Log4jdbc or P6Spy.

Alternatively, you can also write a generic function which takes a Connection, a SQL string and the statement values and returns a PreparedStatement after logging the SQL string and the values. Kickoff example:

public static PreparedStatement prepareStatement(Connection connection, String sql, Object... values) throws SQLException {
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    for (int i = 0; i < values.length; i++) {
        preparedStatement.setObject(i + 1, values[i]);
    }
    logger.debug(sql + " " + Arrays.asList(values));
    return preparedStatement;
}

and use it as

try {
    connection = database.getConnection();
    preparedStatement = prepareStatement(connection, SQL, values);
    resultSet = preparedStatement.executeQuery();
    // ...

Another alternative is to implement a custom PreparedStatement which wraps (decorates) the real PreparedStatement on construction and overrides all the methods so that it calls the methods of the real PreparedStatement and collects the values in all the setXXX() methods and lazily constructs the "actual" SQL string whenever one of the executeXXX() methods is called (quite a work, but most IDE's provides autogenerators for decorator methods, Eclipse does). Finally just use it instead. That's also basically what P6Spy and consorts already do under the hoods.

Object Dump JavaScript

console.log("my object: %o", myObj)

Otherwise you'll end up with a string representation sometimes displaying:

[object Object]

or some such.

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

Difference between `constexpr` and `const`

First of all, both are qualifiers in c++. A variable declared const must be initialized and cannot be changed in the future. Hence generally a variable declared as a const will have a value even before compiling.

But, for constexpr it is a bit different.

For constexpr, you can give an expression that could be evaluated during the compilation of the program.

Obviously, the variable declared as constexper cannot be changed in the future just like const.

hash function for string

Though djb2, as presented on stackoverflow by cnicutar, is almost certainly better, I think it's worth showing the K&R hashes too:

1) Apparently a terrible hash algorithm, as presented in K&R 1st edition (source)

unsigned long hash(unsigned char *str)
{
    unsigned int hash = 0;
    int c;

    while (c = *str++)
        hash += c;

    return hash;
}

2) Probably a pretty decent hash algorithm, as presented in K&R version 2 (verified by me on pg. 144 of the book); NB: be sure to remove % HASHSIZE from the return statement if you plan on doing the modulus sizing-to-your-array-length outside the hash algorithm. Also, I recommend you make the return and "hashval" type unsigned long instead of the simple unsigned (int).

unsigned hash(char *s)
{
    unsigned hashval;

    for (hashval = 0; *s != '\0'; s++)
        hashval = *s + 31*hashval;
    return hashval % HASHSIZE;
}

Note that it's clear from the two algorithms that one reason the 1st edition hash is so terrible is because it does NOT take into consideration string character order, so hash("ab") would therefore return the same value as hash("ba"). This is not so with the 2nd edition hash, however, which would (much better!) return two different values for those strings.

The GCC C++11 hashing functions used for unordered_map (a hash table template) and unordered_set (a hash set template) appear to be as follows.

Code:

// Implementation of Murmur hash for 32-bit size_t.
size_t _Hash_bytes(const void* ptr, size_t len, size_t seed)
{
  const size_t m = 0x5bd1e995;
  size_t hash = seed ^ len;
  const char* buf = static_cast<const char*>(ptr);

  // Mix 4 bytes at a time into the hash.
  while (len >= 4)
  {
    size_t k = unaligned_load(buf);
    k *= m;
    k ^= k >> 24;
    k *= m;
    hash *= m;
    hash ^= k;
    buf += 4;
    len -= 4;
  }

  // Handle the last few bytes of the input array.
  switch (len)
  {
    case 3:
      hash ^= static_cast<unsigned char>(buf[2]) << 16;
      [[gnu::fallthrough]];
    case 2:
      hash ^= static_cast<unsigned char>(buf[1]) << 8;
      [[gnu::fallthrough]];
    case 1:
      hash ^= static_cast<unsigned char>(buf[0]);
      hash *= m;
  };

  // Do a few final mixes of the hash.
  hash ^= hash >> 13;
  hash *= m;
  hash ^= hash >> 15;
  return hash;
}

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

How to exit from Python without traceback?

something like import sys; sys.exit(0) ?

How to find and turn on USB debugging mode on Nexus 4

Navigate to Settings > About Phone > scroll to the bottom > tap Build number seven (7) times. You'll get a short pop-up in the lower area of your display saying that you're now a developer. 2. Go back and now access the Developer options menu, check 'USB debugging' and click OK on the prompt. This Guide Might Help You : How to Enable USB Debugging in Android Phones

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

Create PostgreSQL ROLE (user) if it doesn't exist

Some answers suggested to use pattern: check if role does not exist and if not then issue CREATE ROLE command. This has one disadvantage: race condition. If somebody else creates a new role between check and issuing CREATE ROLE command then CREATE ROLE obviously fails with fatal error.

To solve above problem, more other answers already mentioned usage of PL/pgSQL, issuing CREATE ROLE unconditionally and then catching exceptions from that call. There is just one problem with these solutions. They silently drop any errors, including those which are not generated by fact that role already exists. CREATE ROLE can throw also other errors and simulation IF NOT EXISTS should silence only error when role already exists.

CREATE ROLE throw duplicate_object error when role already exists. And exception handler should catch only this one error. As other answers mentioned it is a good idea to convert fatal error to simple notice. Other PostgreSQL IF NOT EXISTS commands adds , skipping into their message, so for consistency I'm adding it here too.

Here is full SQL code for simulation of CREATE ROLE IF NOT EXISTS with correct exception and sqlstate propagation:

DO $$
BEGIN
CREATE ROLE test;
EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
END
$$;

Test output (called two times via DO and then directly):

$ sudo -u postgres psql
psql (9.6.12)
Type "help" for help.

postgres=# \set ON_ERROR_STOP on
postgres=# \set VERBOSITY verbose
postgres=# 
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
DO
postgres=# 
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
NOTICE:  42710: role "test" already exists, skipping
LOCATION:  exec_stmt_raise, pl_exec.c:3165
DO
postgres=# 
postgres=# CREATE ROLE test;
ERROR:  42710: role "test" already exists
LOCATION:  CreateRole, user.c:337

How to customize the background color of a UITableViewCell?

This is really simple, since OS 3.0 just set the background color of the cell in the willDisplayCell method. You must not set the color in the cellForRowAtIndexPath.

This works for both the plain and grouped style :

Code:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = [UIColor redColor];
}

P.S: Here the documentation extract for willDisplayCell :

"A table view sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. This method gives the delegate a chance to override state-based properties set earlier by the table view, such as selection and background color. After the delegate returns, the table view sets only the alpha and frame properties, and then only when animating rows as they slide in or out."

I've found this information in this post from colionel. Thank him!

Failed to resolve: com.android.support:appcompat-v7:26.0.0

  1. Add this in build.gradle(Project:projectname)

    allprojects {
      repositories {
        jcenter()
        maven { url "https://maven.google.com" }
      }
    }
    
  2. Add this in build.gradle(Module:app)

    dependencies {
      compile 'com.android.support:appcompat-v7:26.1.0'
    }
    

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

How to $watch multiple variable change in angular

$scope.$watch('age + name', function () {
  //called when name or age changed
});

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

It works for me.

git remote add origin https://github.com/repo.git
git push origin master

add the repository URL to the origin in the local working directory

What is a reasonable code coverage % for unit tests (and why)?

Short answer: 60-80%

Long answer: I think it totally depends on the nature of your project. I typically start a project by unit testing every practical piece. By the first "release" of the project you should have a pretty good base percentage based on the type of programming you are doing. At that point you can start "enforcing" a minimum code coverage.

While loop to test if a file exists in bash

do it like this

while true
do
  [ -f /tmp/list.txt ] && break
  sleep 2
done
ls -l /tmp/list.txt

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

This error is also related with a cache issue.

I had the same problem and it was solved just cleaning and building the solution again.

Converting char* to float or double

You are missing an include : #include <stdlib.h>, so GCC creates an implicit declaration of atof and atod, leading to garbage values.

And the format specifier for double is %f, not %d (that is for integers).

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

int main()
{
  char *test = "12.11";
  double temp = strtod(test,NULL);
  float ftemp = atof(test);
  printf("price: %f, %f",temp,ftemp);
  return 0;
}
/* Output */
price: 12.110000, 12.110000

How do I increment a DOS variable in a FOR /F loop?

What about this simple code, works for me and on Windows 7

set cntr=1
:begin
echo %cntr%
set /a cntr=%cntr%+1
if %cntr% EQU 1000 goto end
goto begin

:end

How to store .pdf files into MySQL as BLOBs using PHP?

//Pour inserer :
            $pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
            $filetype = addslashes($_FILES['inputname']['type']);//pour le test 
            $namepdf = addslashes($_FILES['inputname']['name']);            
            if (substr($filetype, 0, 11) == 'application'){
            $mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
            }
//Pour afficher :
            $row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
            foreach($row as $result){
                 $file=$result['pdf'];
            }
            header('Content-type: application/pdf');
            echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

How to make <div> fill <td> height

Modify the background image of the <td> itself.

Or apply some css to the div:

.thatSetsABackgroundWithAnIcon{
    height:100%;
}

Recommendation for compressing JPG files with ImageMagick

I use always:

  • quality in 85
  • progressive (comprobed compression)
  • a very tiny gausssian blur to optimize the size (0.05 or 0.5 of radius) depends on the quality and size of the picture, this notably optimizes the size of the jpeg.
  • Strip any comment or EXIF metadata

in imagemagick should be

convert -strip -interlace Plane -gaussian-blur 0.05 -quality 85% source.jpg result.jpg

or in the newer version:

magick source.jpg -strip -interlace Plane -gaussian-blur 0.05 -quality 85% result.jpg

Source.

From @Fordi in the comments (Don't forget to upvote him if you like this): If you dislike blurring, use -sampling-factor 4:2:0 instead. What this does is reduce the chroma channel's resolution to half, without messing with the luminance resolution that your eyes latch onto. If you want better fidelity in the conversion, you can get a slight improvement without an increase in filesize by specifying -define jpeg:dct-method=float - that is, use the more accurate floating point discrete cosine transform, rather than the default fast integer version.

How to prepend a string to a column value in MySQL?

You can use the CONCAT function to do that:

UPDATE tbl SET col=CONCAT('test',col);

If you want to get cleverer and only update columns which don't already have test prepended, try

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';

How to create a temporary table in SSIS control flow task and then use it in data flow task?

I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.

I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.

Cannot checkout, file is unmerged

i resolved by doing below 2 easy steps :

step 1: git reset Head step 2: git add .

IndentationError: unexpected indent error

import urllib.request
import requests
from bs4 import BeautifulSoup

        r = requests.get('https://icons8.com/icons/set/favicon')

If you try to connect to such a site, you will get an indent error.

import urllib.request
import requests
from bs4 import BeautifulSoup


r = requests.get('https://icons8.com/icons/set/favicon')

Python cares about indents

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

mysql> CREATE USER 'name'@'%' IDENTIFIED BY 'passWord'; Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON . TO 'name'@'%'; Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)

mysql>

  1. Make sure you have your name and % the right way round
  2. Makes sure you have added your port 3306 to any firewall you may be running (although this will give a different error message)

hope this helps someone...

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

Application.Exit() kills your application but there are some instances that it won't close the application.

End is better than Application.Exit().

Undefined index error PHP

TRY

<?php

  $rowID=$productid=$name=$price=$description="";  

   if (isset($_POST['submit'])) {
      $rowID = $_POST['rowID'];
      $productid = $_POST['productid']; //this is line 32 and so on...
      $name = $_POST['name'];
      $price = $_POST['price'];
      $description = $_POST['description'];

}

How to configure custom PYTHONPATH with VM and PyCharm?

In pycharm 5 follow this, https://www.jetbrains.com/pycharm/help/configuring-python-interpreter-for-a-project.html

1)Open the Settings dialog box, and click Project Interpreter page.
2)In the Projects pane, choose the desired project.
3)For the selected project, choose SDK from the list of available Python interpreters and virtual environments.

How to fire an event on class change using jQuery?

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});

UPDATE

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

_x000D_
_x000D_
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  mutations.forEach(function(mutation) {_x000D_
    if (mutation.attributeName === "class") {_x000D_
      var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
      console.log("Class attribute changed to:", attributeValue);_x000D_
    }_x000D_
  });_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
  attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
_x000D_
_x000D_

Be aware that the MutationObserver is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.

How to extract year and month from date in PostgreSQL without using to_char() function?

You Can use EXTRACT function pgSQL

EX- date = 1981-05-31
EXTRACT(MONTH FROM date)
it will Give 05

For more details PGSQL Date-Time

fatal error: mpi.h: No such file or directory #include <mpi.h>

You can execute:

$ mpicc -showme 

result :

gcc -I/Users/<USER_NAME>/openmpi-2.0.1/include -L/Users/<USER_NAME>/openmpi-2.0.1/lib -lmp

This command shows you the necessary libraries to compile mpicc

Example:

$ mpicc -g  -I/Users/<USER_NAME>/openmpi-2.0.1/include -o [nameExec] [objetcs.o...] [program.c] -lm


$ mpicc -g  -I/Users/<USER_NAME>/openmpi-2.0.1/include -o example file_object.o my_program.c otherlib.o -lm

this command generates executable with your program in example, you can execute :

$ ./example

how to calculate binary search complexity

Here a more mathematical way of seeing it, though not really complicated. IMO much clearer as informal ones:

The question is, how many times can you divide N by 2 until you have 1? This is essentially saying, do a binary search (half the elements) until you found it. In a formula this would be this:

1 = N / 2x

multiply by 2x:

2x = N

now do the log2:

log2(2x)    = log2 N
x * log2(2) = log2 N
x * 1         = log2 N

this means you can divide log N times until you have everything divided. Which means you have to divide log N ("do the binary search step") until you found your element.

Cannot make file java.io.IOException: No such file or directory

File.isFile() is false if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.

The issue is that the intermediate directories don't exist. You want to call f.mkdirs() first.

How to remove decimal part from a number in C#

If you just need the integer part of the double then use explicit cast to int.

int number = (int) a;

You may use Convert.ToInt32 Method (Double), but this will round the number to the nearest integer.

value, rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

LEFT JOIN only first row

I've used something else (I think better...) and want to share it:

I created a VIEW that has a "group" clause

CREATE VIEW vCountries AS SELECT * PROVINCES GROUP BY country_code

SELECT * FROM client INNER JOIN vCountries on client_province = province_id

I want to say yet, that I think that we need to do this solution BECAUSE WE DID SOMETHING WRONG IN THE ANALYSIS... at least in my case... but sometimes it's cheaper to do this that to redesign everything...

I hope it helps!

How to push both key and value into an Array in Jquery

You might mean this:

var unEnumeratedArray = [];
var wtfObject = {
                 key    : 'val', 
                 0      : (undefined = 'Look, I\'m defined'),
                 'new'  : 'keyword', 
                 '{!}'  : 'use bracket syntax',
                 '        ': '8 spaces'
                };

for(var key in wtfObject){
    unEnumeratedArray[key] = wtfObject[key];
}
console.log('HAS KEYS PER VALUE NOW:', unEnumeratedArray, unEnumeratedArray[0], 
             unEnumeratedArray.key, unEnumeratedArray['new'], 
             unEnumeratedArray['{!}'], unEnumeratedArray['        ']);

You can set an enumerable for an Object like: ({})[0] = 'txt'; and you can set a key for an Array like: ([])['myKey'] = 'myVal';

Hope this helps :)

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

How to Sort Date in descending order From Arraylist Date in android?

If date in string format convert it to date format for each object :

String argmodifiledDate = "2014-04-06 22:26:15";
SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            try
            {
                this.modifiledDate = format.parse(argmodifiledDate);
            }
            catch (ParseException e)
            {

                e.printStackTrace();
            }

Then sort the arraylist in descending order :

ArrayList<Document> lstDocument= this.objDocument.getArlstDocuments();
        Collections.sort(lstDocument, new Comparator<Document>() {
              public int compare(Document o1, Document o2) {
                  if (o1.getModifiledDate() == null || o2.getModifiledDate() == null)
                    return 0;     
                  return o2.getModifiledDate().compareTo(o1.getModifiledDate());
              }
            });

First char to upper case

public static String cap1stChar(String userIdea)
{
    char[] stringArray = userIdea.toCharArray();
    stringArray[0] = Character.toUpperCase(stringArray[0]);
    return userIdea = new String(stringArray);
}

How can I make a list of installed packages in a certain virtualenv?

list out the installed packages in the virtualenv

step 1:

workon envname

step 2:

pip freeze

it will display the all installed packages and installed packages and versions

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

In a shameless attempt to steal some votes, SecurityProtocol is an Enum with the [Flags] attribute. So you can do this:

[Net.ServicePointManager]::SecurityProtocol = 
  [Net.SecurityProtocolType]::Tls12 -bor `
  [Net.SecurityProtocolType]::Tls11 -bor `
  [Net.SecurityProtocolType]::Tls

Or since this is PowerShell, you can let it parse a string for you:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"

Then you don't technically need to know the TLS version.

I copied and pasted this from a script I created after reading this answer because I didn't want to cycle through all the available protocols to find one that worked. Of course, you could do that if you wanted to.

Final note - I have the original (minus SO edits) statement in my PowerShell profile so it's in every session I start now. It's not totally foolproof since there are still some sites that just fail but I surely see the message in question much less frequently.

What does '&' do in a C++ declaration?

The "&" denotes a reference instead of a pointer to an object (In your case a constant reference).

The advantage of having a function such as

foo(string const& myname) 

over

foo(string const* myname)

is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Since you are passing by reference, the object is not copied, just like if you were passing a pointer.

Your second example:

const string &GetMethodName() { ... }

Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access:

class A
{
  public:
  int bar() const {return someValue;}
  //Big, expensive to copy class
}

class B
{
public:
 A const& getA() { return mA;}
private:
 A mA;
}
void someFunction()
{
 B b = B();
 //Access A, ability to call const functions on A
 //No need to check for null, since reference is guaranteed to be valid.
 int value = b.getA().bar(); 
}

You have to of course be careful to not return invalid references. Compilers will happily compile the following (depending on your warning level and how you treat warnings)

int const& foo() 
{
 int a;

 //This is very bad, returning reference to something on the stack. This will
 //crash at runtime.
 return a; 
}

Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.

Get the last three chars from any string - Java

public String getLastThree(String myString) {
    if(myString.length() > 3)
        return myString.substring(myString.length()-3);
    else
        return myString;
}

Fit website background image to screen size

You can try with

.appBackground {
    position: relative;
    background-image: url(".../img/background.jpg");
    background-repeat:no-repeat;
    background-size:100% 100vh;
}

works for me :)

Loading existing .html file with android WebView

Copy and Paste Your .html file in the assets folder of your Project and add below code in your Activity on onCreate().

        WebView view = new WebView(this);
        view.getSettings().setJavaScriptEnabled(true);
        view.loadUrl("file:///android_asset/**YOUR FILE NAME**.html");
        view.setBackgroundColor(Color.TRANSPARENT);
        setContentView(view);

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

@zdan. Good answer. I'd improve it like this...

I think that the closest you can come to a true return value in PowerShell is to use a local variable to pass the value and never to use return as it may be 'corrupted' by any manner of output situations

function CheckRestart([REF]$retval)
{
    # Some logic
    $retval.Value = $true
}
[bool]$restart = $false
CheckRestart( [REF]$restart)
if ( $restart )
{
    Restart-Computer -Force
}

The $restart variable is used either side of the call to the function CheckRestart making clear the scope of the variable. The return value can by convention be either the first or last parameter declared. I prefer last.

'True' and 'False' in Python

From 6.11. Boolean operations:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.

The expression '/bla/bla/bla' will be treated as true where a Boolean expression is expected (like in an if statement), but the expressions '/bla/bla/bla' is True and '/bla/bla/bla' == True will evaluate to False for the reasons in Ignacio's answer.

Check variable equality against a list of values

In ECMA2016 you can use the includes method. It's the cleanest way I've seen. (Supported by all major browsers)

if([1,3,12].includes(foo)) {
    // ...
}

Disable button in WPF?

In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text that is bound to your TextBox and you would have an ICommand property Apply (or similar) that is bound to the button:

<Button Command="Apply">Apply</Button>

The ICommand interface has a Method CanExecute that is where you return true if (!string.IsNullOrWhiteSpace(this.Text). The rest is done by WPF for you (enabling/disabling, executing the actual command on click).

The linked article explains it in detail.

How to check for null in Twig?

Depending on what exactly you need:

  • is null checks whether the value is null:

    {% if var is null %}
        {# do something #}
    {% endif %}
    
  • is defined checks whether the variable is defined:

    {% if var is not defined %}
        {# do something #}
    {% endif %}
    

Additionally the is sameas test, which does a type strict comparison of two values, might be of interest for checking values other than null (like false):

{% if var is sameas(false) %}
    {# do something %}
{% endif %}

How can I read numeric strings in Excel cells as string (not numbers)?

I don't think we had this class back when you asked the question, but today there is an easy answer.

What you want to do is use the DataFormatter class. You pass this a cell, and it does its best to return you a string containing what Excel would show you for that cell. If you pass it a string cell, you'll get the string back. If you pass it a numeric cell with formatting rules applied, it will format the number based on them and give you the string back.

For your case, I'd assume that the numeric cells have an integer formatting rule applied to them. If you ask DataFormatter to format those cells, it'll give you back a string with the integer string in it.

Also, note that lots of people suggest doing cell.setCellType(Cell.CELL_TYPE_STRING), but the Apache POI JavaDocs quite clearly state that you shouldn't do this! Doing the setCellType call will loose formatting, as the javadocs explain the only way to convert to a String with formatting remaining is to use the DataFormatter class.

Sorting arrays in NumPy by column

From the Python documentation wiki, I think you can do:

a = ([[1, 2, 3], [4, 5, 6], [0, 0, 1]]); 
a = sorted(a, key=lambda a_entry: a_entry[1]) 
print a

The output is:

[[[0, 0, 1], [1, 2, 3], [4, 5, 6]]]

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

ACCESSING LOCAL WEBSITE WITH IIS without Physical Path Authentication

  1. Make sure you have installed URL Rewrite to your IIS Manager

enter image description here

  1. Open the URL Rewrite application then navigate to Inbound Rules>Import Rules

enter image description here

  1. To import the rule, click the browse button then locate your .htaccess file then click import button

enter image description here

  1. The text labeled with red are errors that are not accepted by IIS, so you have to remove them by clicking the errors in the converted rules and remove the text from the rewrite rules. Once you have get rid of the errors Click the APPLY button located at the top right corner. Then try to access your site without engaging users into the pool auth.

enter image description here

I hope it helps. That's what I did.

IntelliJ IDEA generating serialVersionUID

After spending some time on Serialization, I find that, we should not generate serialVersionUID with some random value, we should give it a meaningful value.

Here is a details comment on this. I am coping the comment here.

Actually, you should not be "generating" serial version UIDs. It is a dumb "feature" that stems from the general misunderstanding of how that ID is used by Java. You should be giving these IDs meaningful, readable values, e.g. starting with 1L, and incrementing them each time you think the new version of the class should render all previous versions (that might be previously serialized) obsolete. All utilities that generate such IDs basically do what the JVM does when the ID is not defined: they generate the value based on the content of the class file, hence coming up with unreadable meaningless long integers. If you want each and every version of your class to be distinct (in the eyes of the JVM) then you should not even specify the serialVersionUID value isnce the JVM will produce one on the fly, and the value of each version of your class will be unique. The purpose of defining that value explicitly is to tell the serialization mechanism to treat different versions of the class that have the same SVUID as if they are the same, e.g. not to reject the older serialized versions. So, if you define the ID and never change it (and I assume that's what you do since you rely on the auto-generation, and you probably never re-generate your IDs) you are ensuring that all - even absolutely different - versions of your class will be considered the same by the serialization mechanism. Is that what you want? If not, and if you indeed want to have control over how your objects are recognized, you should be using simple values that you yourself can understand and easily update when you decide that the class has changed significantly. Having a 23-digit value does not help at all.

Hope this helps. Good luck.

How can I show data using a modal when clicking a table row (using bootstrap)?

The solution from PSL will not work in Firefox. FF accepts event only as a formal parameter. So you have to find another way to identify the selected row. My solution is something like this:

...
$('#mySelector')
  .on('show.bs.modal', function(e) {
  var mid;


  if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) 
    mid = $(e.relatedTarget).data('id');
  else
    mid = $(event.target).closest('tr').data('id');

...

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

What is the correct way to free memory in C#

Objects are eligable for garbage collection once they go out of scope become unreachable (thanks ben!). The memory won't be freed unless the garbage collector believes you are running out of memory.

For managed resources, the garbage collector will know when this is, and you don't need to do anything.

For unmanaged resources (such as connections to databases or opened files) the garbage collector has no way of knowing how much memory they are consuming, and that is why you need to free them manually (using dispose, or much better still the using block)

If objects are not being freed, either you have plenty of memory left and there is no need, or you are maintaining a reference to them in your application, and therefore the garbage collector will not free them (in case you actually use this reference you maintained)

How to get an MD5 checksum in PowerShell

Sample for right-click menu option as well:

[HKEY_CLASSES_ROOT\*\shell\SHA1 PS check\command]
@="C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command Get-FileHash -Algorithm SHA1 '%1'"

Data binding in React

Data binding in React can be achieved by using a controlled input. A controlled input is achieved by binding the value to a state variable and a onChange event to change the state as the input value changes.

See the below snippet

_x000D_
_x000D_
class App extends React.Component {
  constructor() {
    super();
    this.state = { value: 'Hello World' };
  }
  handleChange = (e) => {
    this.setState({ value: e.target.value });
  };
  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
        />
        <p>{this.state.value}</p>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>
_x000D_
_x000D_
_x000D_


Update: React Hooks

Here is an equivalent function component of the class defined above.

_x000D_
_x000D_
const { useState } = React;

const App = () => {
  const [value, setValue] = useState('Hello World');
  const handleChange = (e) => setValue(e.target.value);
  return (
    <div>
      <input type="text" value={value} onChange={handleChange} />
      <p>{value}</p>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Error: Specified cast is not valid. (SqlManagerUI)

I had a similar error "Specified cast is not valid" restoring from SQL Server 2012 to SQL Server 2008 R2

First I got the MDF and LDF Names:

RESTORE FILELISTONLY 
FROM  DISK = N'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak' 
GO

Second I restored with a MOVE using those names returned:

RESTORE DATABASE Davincis3 
FROM DISK = 'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak'
WITH 
   MOVE 'JQueryExampleDb' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.mdf', 
   MOVE 'JQueryExampleDB_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.ldf', 
REPLACE
GO  

I have no clue as to the name "JQueryExampleDb", but this worked for me.

Nevertheless, backups (and databases) are not backwards compatible with older versions.

iOS for VirtualBox

You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.

Scrollview vertical and horizontal in android

Playing with the code, you can put an HorizontalScrollView into an ScrollView. Thereby, you can have the two scroll method in the same view.

Source : http://androiddevblog.blogspot.com/2009/12/creating-two-dimensions-scroll-view.html

I hope this could help you.

php timeout - set_time_limit(0); - don't work

Checkout this, This is from PHP MANUAL, This may help you.

If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:

<?php

require_once('db.php');

$stmt = $db->query($sql);

while ($row = $stmt->fetchRow()) {
    set_time_limit(0);
    // your code here
}

?>

Invoking a jQuery function after .each() has completed

It's probably to late but i think this code work...

$blocks.each(function(i, elm) {
 $(elm).fadeOut(200, function() {
  $(elm).remove();
 });
}).promise().done( function(){ alert("All was done"); } );

Difference between r+ and w+ in fopen()

There are 2 differences, unlike r+, w+ will:

  • create the file if it does not already exist
  • first truncate it, i.e., will delete its contents

How to set breakpoints in inline Javascript in Google Chrome?

I came across this issue, however my inline function was withing an angularJS view. Therefore on the load i could not access the inline script to add the debug, as only the index.html was available in the sources tab of the debugger.

This meant that when i was opening the particular view with my inline (had no choice on this) it was not accessible.

The onlly way i was able to hit it was to put an erroneous function or call inside the inline JS function.

My solution included :

function doMyInline(data) {
        //Throw my undefined error here. 
        $("select.Sel").debug();

        //This is the real onclick i was passing to 
        angular.element(document.getElementById(data.id)).scope().doblablabla(data.id);
    }

This mean when i clicked on my button, i was then prompted in the chrome consolse.

Uncaught TypeError: undefined is not a function 

The important thing here was the source of this : VM5658:6 clicking on this allowed me to step through the inline and hold the break point there for later..

Extremely convoluted way of reaching it.. But it worked and might prove useful for when dealing with Single page apps which dynamically load your views.

The VM[n] has no significant value, and the n on equates to the script ID. This info can be found here : Chrome "[VM]"

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

How to scroll to bottom in a ScrollView on activity startup

This is the best way of doing this.

scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            scrollView.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
});

Getting results between two dates in PostgreSQL

 SELECT *
   FROM mytable
  WHERE (start_date, end_date) OVERLAPS ('2012-01-01'::DATE, '2012-04-12'::DATE);

Datetime functions is the relevant section in the docs.

JQuery: How to get selected radio button value?

Probably the best method (particularly if you want to be able to post a default value), would be to have a hidden radio button that starts out as selected and has your default value. So something like this:

<input type="radio" name="myradiobutton" value="0" checked="checked" style="display:none;" />
<input type="radio" name="myradiobutton" value="1" />1
<input type="radio" name="myradiobutton" value="2" />2
<input type="radio" name="myradiobutton" value="3" />3

If you can't modify your html directly, you could add it via script:

$(function() {
    $('input[name=myradiobutton]:radio:first').before('<input type="radio" name="myradiobutton" value="0" checked="checked" style="display:none;" />');
});

Here's a demo of that: http://jsfiddle.net/Ender/LwPCv/

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

How to use both onclick and target="_blank"

Just use window.open():

window.open('Prosjektplan.pdf')

Anyway, what guys are saying on comments is true. You better use <a target="_blank"> instead of click events.

Writing to CSV with Python adds blank lines

You need to open the file in binary b mode to take care of blank lines in Python 2. This isn't required in Python 3.

So, change open('test.csv', 'w') to open('test.csv', 'wb').

Select multiple rows with the same value(s)

One way of doing this is via an exists clause:

select * from genes g
where exists
(select null from genes g1
 where g.locus = g1.locus and g.chromosome = g1.chromosome and g.id <> g1.id)

Alternatively, in MySQL you can get a summary of all matching ids with a single table access, using group_concat:

select group_concat(id) matching_ids, chromosome, locus 
from genes
group by chromosome, locus
having count(*) > 1

What are the differences between delegates and events?

An event in .net is a designated combination of an Add method and a Remove method, both of which expect some particular type of delegate. Both C# and vb.net can auto-generate code for the add and remove methods which will define a delegate to hold the event subscriptions, and add/remove the passed in delegagte to/from that subscription delegate. VB.net will also auto-generate code (with the RaiseEvent statement) to invoke the subscription list if and only if it is non-empty; for some reason, C# doesn't generate the latter.

Note that while it is common to manage event subscriptions using a multicast delegate, that is not the only means of doing so. From a public perspective, a would-be event subscriber needs to know how to let an object know it wants to receive events, but it does not need to know what mechanism the publisher will use to raise the events. Note also that while whoever defined the event data structure in .net apparently thought there should be a public means of raising them, neither C# nor vb.net makes use of that feature.

git clone through ssh

I did : git clone --bare "/GITREPOSITORIES/RepoA" "ssh://luc@EERSTENASDS119J/volume1/RepoA" Result : fatal: destination path 'ssh://luc@EERSTENASDS119J/volume1/RepoA' already exists and is not an empty directory.

The system created a directory ssh://luc@EERSTENASDS119J/volume1/RepoA in my current path.

So git clone did not interpret the URL specification. Used the workaround of Alec.

Online SQL syntax checker conforming to multiple databases

You could try a formatter like this

They will always be limited because they don't (and can't) know what user defined functions you may have defined in your database (or which built-in functions you have or don't have access to).

You could also look at ANTLR (but that would be an offline solution)

QByteArray to QString

Qt 4.8

QString(byteArray).toStdString();

Qt 5.12

byteArray.toStdString();

How do I convert a long to a string in C++?

One of the things not covered by anybody so far, to help you think about the problem further, is what format should a long take when it is cast to a string.

Just have a look at a spreedsheet program (like Calc/Excel). Do you want it rounded to the nearest million, with brackets if it's negative, always to show the sign.... Is the number realy a representation of something else, should you show it in Oractal or Hex instead?

The answers so far have given you some default output, but perhaps not the right ones.

Count number of iterations in a foreach loop

count($Contents);

or

sizeof($Contents);

Java, how to compare Strings with String Arrays

Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.

Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?

...or do I misunderstand your question?

What does %>% mean in R

matrix multiplication, see the following example:

> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
     [,1] [,2] [,3]
[1,]    1    5    1
[2,]    3    8    3
[3,]    4    9    3
> 
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
> 
> B
     [,1] [,2] [,3]
[1,]    2    8    3
[2,]    4    9    4
[3,]    5    2    5
> 
> 
> A %*% B
     [,1] [,2] [,3]
[1,]   27   55   28
[2,]   53  102   56
[3,]   59  119   63

> B %*% A
     [,1] [,2] [,3]
[1,]   38  101   35
[2,]   47  128   43
[3,]   31   86   26

Also see:

http://en.wikipedia.org/wiki/Matrix_multiplication

If this does not follow the size of matrix rule you will get the error:

> A <- matrix(c(1,2,3,4,5,6), 3,2)
    > A
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)

> B
         [,1] [,2] [,3]
    [1,]    3    4    4
    [2,]    1    4    4
    [3,]    3    4    3
    > A%*%B
    Error in A %*% B : non-conformable arguments

Comparing two arrays & get the values which are not common

Your results will not be helpful unless the arrays are first sorted. To sort an array, run it through Sort-Object.

$x = @(5,1,4,2,3)
$y = @(2,4,6,1,3,5)

Compare-Object -ReferenceObject ($x | Sort-Object) -DifferenceObject ($y | Sort-Object)

C# Collection was modified; enumeration operation may not execute

The error tells you EXACTLY what the problem is (and running in the debugger or reading the stack trace will tell you exactly where the problem is):

C# Collection was modified; enumeration operation may not execute.

Your problem is the loop

foreach (KeyValuePair<int, int> kvp in rankings) {
    //
}

wherein you modify the collection rankings. In particular, the offensive line is

rankings[kvp.Key] = rankings[kvp.Key] + 4;

Before you enter the loop, add the following line:

var listOfRankingsToModify = new List<int>();

Replace the offending line with

listOfRankingsToModify.Add(kvp.Key);

and after you exit the loop

foreach(var key in listOfRankingsToModify) {
    rankings[key] = rankings[key] + 4;
}

That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.

How can I autoformat/indent C code in vim?

I find that clang-format works well.

There are some example keybindings in the clang documentation

I prefer to use the equalprg binding in vim. This allows you to invoke clang-format with G=gg or other = indent options.

Just put the following in your .vimrc file:

autocmd FileType c,cpp setlocal equalprg=clang-format

How to get current route

Inject Location to your component and read location.path(); You need to add ROUTER_DIRECTIVES somewhere so Angular can resolve Location. You need to add import: [RouterModule] to the module.

Update

In the V3 (RC.3) router you can inject ActivatedRoute and access more details using its snapshot property.

constructor(private route:ActivatedRoute) {
  console.log(route);
}

or

constructor(private router:Router) {
  router.events.subscribe(...);
}

See also Angular 2 router event listener

Google Map API v3 ~ Simply Close an infowindow?

infowindow.open(null,null);

will close opened infowindow. It will work same as

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

Try this one, if null set 0 or something

return command.ExecuteScalar() == DBNull.Value ? 0 : (double)command.ExecuteScalar();

Centering a background image, using CSS

The only thing that worked for me is..

margin: 0 auto

How do I determine if a checkbox is checked?

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<label><input class="lifecheck" id="lifecheck" type="checkbox" checked >Lives</label>_x000D_
_x000D_
<script type="application/javascript" >_x000D_
    lfckv = document.getElementsByClassName("lifecheck");_x000D_
    if (true === lfckv[0].checked) {_x000D_
      alert('the checkbox is checked');_x000D_
    }_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

so after you can add event in javascript to have dynamical event affected with the checkbox .

thanks

DateTime2 vs DateTime in SQL Server

I think DATETIME2 is the better way to store the date, because it has more efficiency than the DATETIME. In SQL Server 2008 you can use DATETIME2, it stores a date and time, takes 6-8 bytes to store and has a precision of 100 nanoseconds. So anyone who needs greater time precision will want DATETIME2.

"java.lang.OutOfMemoryError : unable to create new native Thread"

I had this same issue and it turned out to be an improper usage of an java API. I was initializing a builder in a batch processing method that was that not supposed to be initiallized more than once.

Basically I was doing something like:

for (batch in batches) {
    process_batch(batch)
}

def process_batch(batch) {
    var client = TransportClient.builder().build()
    client.processList(batch)
}

when I should have done this:

for (batch in batches) {
    var client = TransportClient.builder().build()
    process_batch(batch, client)
}

def process_batch(batch, client) {
    client.processList(batch)
}

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

Java and HTTPS url connection without downloading certificate

If you are using any Payment Gateway to hit any url just to send a message, then i used a webview by following it : How can load https url without use of ssl in android webview

and make a webview in your activity with visibility gone. What you need to do : just load that webview.. like this:

 webViewForSms.setWebViewClient(new SSLTolerentWebViewClient());
                webViewForSms.loadUrl(" https://bulksms.com/" +
                        "?username=test&password=test@123&messageType=text&mobile="+
                        mobileEditText.getText().toString()+"&senderId=ATZEHC&message=Your%20OTP%20for%20A2Z%20registration%20is%20124");

Easy.

You will get this: SSLTolerentWebViewClient from this link: How can load https url without use of ssl in android webview

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

Use absolute positioning

.child-div {
    position:absolute;
    left:0;
    right:0;
}

How do I sort a VARCHAR column in SQL server that contains numbers?

you can always convert your varchar-column to bigint as integer might be too short...

select cast([yourvarchar] as BIGINT)

but you should always care for alpha characters

where ISNUMERIC([yourvarchar] +'e0') = 1

the +'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber

this would lead to your statement

SELECT
  *
FROM
  Table
ORDER BY
   ISNUMERIC([yourvarchar] +'e0') DESC
 , LEN([yourvarchar]) ASC

the first sorting column will put numeric on top. the second sorts by length, so 10 will preceed 0001 (which is stupid?!)

this leads to the second version:

SELECT
      *
    FROM
      Table
    ORDER BY
       ISNUMERIC([yourvarchar] +'e0') DESC
     , RIGHT('00000000000000000000'+[yourvarchar], 20) ASC

the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)

so third version:

 SELECT
          *
        FROM
          Table
        ORDER BY
           ISNUMERIC([yourvarchar] +'e0') DESC
         , CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1
                THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC
                ELSE LTRIM(RTRIM([yourvarchar]))
           END ASC

now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed

Angular2, what is the correct way to disable an anchor element?

My answer might be late for this post. It can be achieved through inline css within anchor tag only.

<a [routerLink]="['/user']" [style.pointer-events]="isDisabled ?'none':'auto'">click-label</a>

Considering isDisabled is a property in component which can be true or false.

Plunker for it: https://embed.plnkr.co/TOh8LM/

Replace a value if null or undefined in JavaScript

Logical nullish assignment, 2020+ solution

A new operator has been added, ??=. This is equivalent to value = value ?? defaultValue.

||= and &&= are similar, links below.

This checks if left side is undefined or null, short-circuiting if already defined. If not, the left side is assigned the right-side value.

Basic Examples

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

// Equivalent to
a = a ?? true

Object/Array Examples

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

Functional Example

function config(options) {
    options.duration ??= 100
    options.speed ??= 25
    return options
}

config({ duration: 555 })   // { duration: 555, speed: 25 }
config({})                  // { duration: 100, speed: 25 }
config({ duration: null })  // { duration: 100, speed: 25 }

??= Browser Support Nov 2020 - 77%

??= Mozilla Documentation

||= Mozilla Documentation

&&= Mozilla Documentation

Executing an EXE file using a PowerShell script

& "C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode

or

[System.Diagnostics.Process]::Start("C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe", "C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode")

UPDATE: sorry I missed "(I invoked the command using the "&" operator)" sentence. I had this problem when I was evaluating the path dynamically. Try Invoke-Expression construction:

Invoke-Expression "& `"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe`" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode"

Readably print out a python dict() sorted by key

I had the same problem you had. I used a for loop with the sorted function passing in the dictionary like so:

for item in sorted(mydict):
    print(item)

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

Parallel foreach with asynchronous lambda

The following is set to work with IAsyncEnumerable but can be modified to use IEnumerable by just changing the type and removing the "await" on the foreach. It's far more appropriate for large sets of data than creating countless parallel tasks and then awaiting them all.

    public static async Task ForEachAsyncConcurrent<T>(this IAsyncEnumerable<T> enumerable, Func<T, Task> action, int maxDegreeOfParallelism, int? boundedCapacity = null)
    {
        ActionBlock<T> block = new ActionBlock<T>(
           action, 
           new ExecutionDataflowBlockOptions 
           { 
             MaxDegreeOfParallelism = maxDegreeOfParallelism, 
             BoundedCapacity = boundedCapacity ?? maxDegreeOfParallelism * 3 
           });

        await foreach (T item in enumerable)
        {
           await block.SendAsync(item).ConfigureAwait(false);
        }

        block.Complete();
        await block.Completion;
    }

How to declare std::unique_ptr and what is the use of it?

From cppreference, one of the std::unique_ptr constructors is

explicit unique_ptr( pointer p ) noexcept;

So to create a new std::unique_ptr is to pass a pointer to its constructor.

unique_ptr<int> uptr (new int(3));

Or it is the same as

int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);

The different is you don't have to clean up after using it. If you don't use std::unique_ptr (smart pointer), you will have to delete it like this

delete int_ptr;

when you no longer need it or it will cause a memory leak.

How can I strip HTML tags from a string in ASP.NET?

string result = Regex.Replace(anytext, @"<(.|\n)*?>", string.Empty);

jQuery if checkbox is checked

to check input and get confirm by check box ,use this script...

_x000D_
_x000D_
 $(document).on("change", ".inputClass", function () {
    if($(this).is(':checked')){
     confirm_message = $(this).data('confirm');
       var confirm_status = confirm(confirm_message);
                        if (confirm_status == true) {
                           //doing somethings...
                         }
                   }});  
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> check action </lable>
<input class="inputClass" type="checkbox" data-confirm="are u sure to do ...?" >
_x000D_
_x000D_
_x000D_

Creating a thumbnail from an uploaded image

UPDATE:

If you want to take advantage of Imagick (if it is installed on your server). Note: I didn't use Imagick's nature writeFile because I was having issues with it on my server. File put contents works just as well.

<?php
/**
 * 
 * Generate Thumbnail using Imagick class
 *  
 * @param string $img
 * @param string $width
 * @param string $height
 * @param int $quality
 * @return boolean on true
 * @throws Exception
 * @throws ImagickException
 */
function generateThumbnail($img, $width, $height, $quality = 90)
{
    if (is_file($img)) {
        $imagick = new Imagick(realpath($img));
        $imagick->setImageFormat('jpeg');
        $imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
        $imagick->setImageCompressionQuality($quality);
        $imagick->thumbnailImage($width, $height, false, false);
        $filename_no_ext = reset(explode('.', $img));
        if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {
            throw new Exception("Could not put contents.");
        }
        return true;
    }
    else {
        throw new Exception("No valid image provided with {$img}.");
    }
}

// example usage
try {
    generateThumbnail('test.jpg', 100, 50, 65);
}
catch (ImagickException $e) {
    echo $e->getMessage();
}
catch (Exception $e) {
    echo $e->getMessage();
}
?>

I have been using this, just execute the function after you store the original image and use that location to create the thumbnail. Edit it to your liking...

function makeThumbnails($updir, $img, $id)
{
    $thumbnail_width = 134;
    $thumbnail_height = 189;
    $thumb_beforeword = "thumb";
    $arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
    $original_width = $arr_image_details[0];
    $original_height = $arr_image_details[1];
    if ($original_width > $original_height) {
        $new_width = $thumbnail_width;
        $new_height = intval($original_height * $new_width / $original_width);
    } else {
        $new_height = $thumbnail_height;
        $new_width = intval($original_width * $new_height / $original_height);
    }
    $dest_x = intval(($thumbnail_width - $new_width) / 2);
    $dest_y = intval(($thumbnail_height - $new_height) / 2);
    if ($arr_image_details[2] == IMAGETYPE_GIF) {
        $imgt = "ImageGIF";
        $imgcreatefrom = "ImageCreateFromGIF";
    }
    if ($arr_image_details[2] == IMAGETYPE_JPEG) {
        $imgt = "ImageJPEG";
        $imgcreatefrom = "ImageCreateFromJPEG";
    }
    if ($arr_image_details[2] == IMAGETYPE_PNG) {
        $imgt = "ImagePNG";
        $imgcreatefrom = "ImageCreateFromPNG";
    }
    if ($imgt) {
        $old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
        $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
        imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
        $imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
    }
}

The above function creates images with a uniform thumbnail size. If the image doesn't have the same dimensions as the specified thumbnail size (proportionally), it just has blackspace on the top and bottom.

Chrome ignores autocomplete="off"

Change input type attribute to type="search".

Google doesn't apply auto-fill to inputs with a type of search.

How can I listen for keypress event on the whole page?

yurzui's answer didn't work for me, it might be a different RC version, or it might be a mistake on my part. Either way, here's how I did it with my component in Angular2 RC4 (which is now quite outdated).

@Component({
    ...
    host: {
        '(document:keydown)': 'handleKeyboardEvents($event)'
    }
})
export class MyComponent {
    ...
    handleKeyboardEvents(event: KeyboardEvent) {
        this.key = event.which || event.keyCode;
    }
}

XAMPP: Couldn't start Apache (Windows 10)

In my case it was a simple case of removing IIS because Windows 10 comes with IIS (Internet Information Service) pre installed - that conflicts with XAMPP because these both servers try to use the port 80. If you don't want to use IIS and keep using XAMPP

  1. Go to run/search in Windows 10
  2. Search for 'optional features'
  3. On that list untick Internet Information Service (IIS)

Then restart.

Squaring all elements in a list

Use a list comprehension (this is the way to go in pure Python):

>>> l = [1, 2, 3, 4]
>>> [i**2 for i in l]
[1, 4, 9, 16]

Or numpy (a well-established module):

>>> numpy.array([1, 2, 3, 4])**2
array([ 1,  4,  9, 16])

In numpy, math operations on arrays are, by default, executed element-wise. That's why you can **2 an entire array there.

Other possible solutions would be map-based, but in this case I'd really go for the list comprehension. It's Pythonic :) and a map-based solution that requires lambdas is slower than LC.

Angular 2: Get Values of Multiple Checked Checkboxes

Here's a solution without map, 'checked' properties and FormControl.

app.component.html:

<div *ngFor="let item of options">
  <input type="checkbox" 
  (change)="onChange($event.target.checked, item)"
  [checked]="checked(item)"
>
  {{item}}
</div>

app.component.ts:

  options = ["1", "2", "3", "4", "5"]
  selected = ["1", "2", "5"]

  // check if the item are selected
  checked(item){
    if(this.selected.indexOf(item) != -1){
      return true;
    }
  }

  // when checkbox change, add/remove the item from the array
  onChange(checked, item){
    if(checked){
    this.selected.push(item);
    } else {
      this.selected.splice(this.selected.indexOf(item), 1)
    }
  }

DEMO

How can I recover a lost commit in Git?

Another way to get to the deleted commit is with the git fsck command.

git fsck --lost-found

This will output something like at the last line:

dangling commit xyz

We can check that it is the same commit using reflog as suggested in other answers. Now we can do a git merge

git merge xyz

Note:
We cannot get the commit back with fsck if we have already run a git gc command which will remove the reference to the dangling commit.

How do I encode URI parameter values?

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

php pdo: get the columns name of a table

$sql = "select column_name from information_schema.columns where table_name = 'myTable'";

PHP function credits : http://www.sitepoint.com/forums/php-application-design-147/get-pdo-column-name-easy-way-559336.html

    function getColumnNames(){ 

    $sql = "select column_name from information_schema.columns where table_name = 'myTable'";
    #$sql = 'SHOW COLUMNS FROM ' . $this->table; 

    $stmt = $this->connection->prepare($sql); 

    try {     
        if($stmt->execute()){ 
            $raw_column_data = $stmt->fetchAll(PDO::FETCH_ASSOC); 

            foreach($raw_column_data as $outer_key => $array){ 
                foreach($array as $inner_key => $value){ 
                            if (!(int)$inner_key){ 
                                $this->column_names[] = $value; 
                            } 
                } 
            } 
            } 
            return $this->column_names; 
        } catch (Exception $e){ 
                return $e->getMessage(); //return exception 
        }         
    }  

pthread_join() and pthread_exit()

In pthread_exit, ret is an input parameter. You are simply passing the address of a variable to the function.

In pthread_join, ret is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL.

Long explanation:

In pthread_join, you get back the address passed to pthread_exit by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Go to Eclipse folder, locate eclipse.ini file, add following entry (before -vmargs if present):

-vm
C:\Program Files\Java\jdk1.7.0_10\bin\javaw.exe

Save file and execute eclipse.exe.

gcc error: wrong ELF class: ELFCLASS64

It turns out the compiler version I was using did not match the compiled version done with the coreset.o.

One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.

How to install python-dateutil on Windows?

Using setup from distutils.core instead of setuptools in setup.py worked for me, too:

#from setuptools import setup
from distutils.core import setup

How to rename files and folder in Amazon S3?

There is no direct method to rename a file in S3. What you have to do is copy the existing file with a new name (just set the target key) and delete the old one.

What is the most efficient way to store tags in a database?

Items should have an "ID" field, and Tags should have an "ID" field (Primary Key, Clustered).

Then make an intermediate table of ItemID/TagID and put the "Perfect Index" on there.

JavaScript code for getting the selected value from a combo box

I use this

var e = document.getElementById('ticket_category_clone').value;

Notice that you don't need the '#' character in javascript.

    function check () {

    var str = document.getElementById('ticket_category_clone').value;

      if (str==="Hardware")
      {
        SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
      }

    }

SPICEWORKS.app.helpdesk.ready(check);?

SQL UPDATE with sub-query that references the same table in MySQL

UPDATE user_account student

SET (student.student_education_facility_id) = (

   SELECT teacher.education_facility_id

   FROM user_account teacher

   WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'

)

WHERE student.user_type = 'ROLE_STUDENT';

Change User Agent in UIWebView

Try this in the AppDelegate.m

+ (void)initialize 

{

    // Set user agent (the only problem is that we can’t modify the User-Agent later in the program)

    // iOS 5.1

    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@”Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3”, @”UserAgent”, nil];


    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

}

How to call a RESTful web service from Android?

Here is my Library That I have created for simple Webservice Calling,

You can use this by adding a one line gradle dependency -

compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'

Here is the demonstration of using.

https://github.com/vishalchhodwani1992/httpLibrary

Dropping Unique constraint from MySQL table

The constraint could be removed with syntax:

ALTER TABLE

As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name: ALTER TABLE tbl_name DROP CONSTRAINT symbol;

Example:

CREATE TABLE tab(id INT, CONSTRAINT unq_tab_id UNIQUE(id));

-- checking constraint name if autogenerated
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'tab';

-- dropping constraint
ALTER TABLE tab DROP CONSTRAINT unq_tab_id;

db<>fiddle demo

How can I remove punctuation from input text in Java?

You can use following regular expression construct

Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~

inputString.replaceAll("\\p{Punct}", "");

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Well there's the Network Connections preference page; you can add proxies there. I don't know much about it; I don't know if the Maven integration plugins will use the proxies defined there.

You can find it at Window...Preferences, then General...Network Connections.

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

Fixed height and width for bootstrap carousel

Apply following style to carousel listbox.

_x000D_
_x000D_
<div class="carousel-inner" role="listbox" style=" width:100%; height: 500px !important;">_x000D_
_x000D_
..._x000D_
_x000D_
</div
_x000D_
_x000D_
_x000D_

How to send post request to the below post method using postman rest client

The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

https://www.getpostman.com/docs/requests

/exclude in xcopy just for a file type

For excluding multiple file types, you can use '+' to concatenate other lists. For example:

xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan

Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/

javascript onclick increment number

No need to worry for incrementing/decrementing numbers using Javascript. Now HTML itself provides an easy way for it.

<input type="number" value="50">

It is that simple.The problem is that it works fine only in some browsers.Mozilla has not yet supported this feature.

Is there a label/goto in Python?

To answer the @ascobol's question using @bobince's suggestion from the comments:

for i in range(5000):
    for j in range(3000):
        if should_terminate_the_loop:
           break
    else: 
        continue # no break encountered
    break

The indent for the else block is correct. The code uses obscure else after a loop Python syntax. See Why does python use 'else' after for and while loops?

Eclipse CDT: Symbol 'cout' could not be resolved

If all else fails, like it did in my case, then just disable annotations. I started a c++11 project with own makefile but couldn't fix all the problems. Even if you disable annotations, eclipse will still be able to help you do some autocompletion. Most importantly, the debugger still works!

What is the difference between LATERAL and a subquery in PostgreSQL?

Database table

Having the following blog database table storing the blogs hosted by our platform:

Blog table

And, we have two blogs currently hosted:

id created_on title url
1 2013-09-30 Vlad Mihalcea's Blog https://vladmihalcea.com
2 2017-01-22 Hypersistence https://hypersistence.io

Getting our report without using the SQL LATERAL JOIN

We need to build a report that extracts the following data from the blog table:

  • the blog id
  • the blog age, in years
  • the date for the next blog anniversary
  • the number of days remaining until the next anniversary.

If you're using PostgreSQL, then you have to execute the following SQL query:

SELECT
  b.id as blog_id,
  extract(
    YEAR FROM age(now(), b.created_on)
  ) AS age_in_years,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
ORDER BY blog_id

As you can see, the age_in_years has to be defined three times because you need it when calculating the next_anniversary and days_to_next_anniversary values.

And, that's exactly where LATERAL JOIN can help us.

Getting the report using the SQL LATERAL JOIN

The following relational database systems support the LATERAL JOIN syntax:

  • Oracle since 12c
  • PostgreSQL since 9.3
  • MySQL since 8.0.14

SQL Server can emulate the LATERAL JOIN using CROSS APPLY and OUTER APPLY.

LATERAL JOIN allows us to reuse the age_in_years value and just pass it further when calculating the next_anniversary and days_to_next_anniversary values.

The previous query can be rewritten to use the LATERAL JOIN, as follows:

SELECT
  b.id as blog_id,
  age_in_years,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
CROSS JOIN LATERAL (
  SELECT
    cast(
      extract(YEAR FROM age(now(), b.created_on)) AS int
    ) AS age_in_years
) AS t
ORDER BY blog_id

And, the age_in_years value can be calculated one and reused for the next_anniversary and days_to_next_anniversary computations:

blog_id age_in_years next_anniversary days_to_next_anniversary
1 7 2021-09-30 295
2 3 2021-01-22 44

Much better, right?

The age_in_years is calculated for every record of the blog table. So, it works like a correlated subquery, but the subquery records are joined with the primary table and, for this reason, we can reference the columns produced by the subquery.

Android SQLite Example

Sqlite helper class helps us to manage database creation and version management. SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade() methods of SQLiteOpenHelper. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete() to create, read, update and delete rows of your table.

Example to create a MyEmployees table and to select and insert records:

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "DBName";

    private static final int DATABASE_VERSION = 2;

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table MyEmployees
                                 ( _id integer primary key,name text not null);";

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

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    // Method is called during an upgrade of the database,
    @Override
    public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
        Log.w(MyDatabaseHelper.class.getName(),
                         "Upgrading database from version " + oldVersion + " to "
                         + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS MyEmployees");
        onCreate(database);
    }
}

Now you can use this class as below,

public class MyDB{  

    private MyDatabaseHelper dbHelper;  

    private SQLiteDatabase database;  

    public final static String EMP_TABLE="MyEmployees"; // name of table 

    public final static String EMP_ID="_id"; // id value for employee
    public final static String EMP_NAME="name";  // name of employee

    /** 
     * 
     * @param context 
     */  
    public MyDB(Context context){  
        dbHelper = new MyDatabaseHelper(context);  
        database = dbHelper.getWritableDatabase();  
    }


    public long createRecords(String id, String name){  
        ContentValues values = new ContentValues();  
        values.put(EMP_ID, id);  
        values.put(EMP_NAME, name);  
        return database.insert(EMP_TABLE, null, values);  
    }    

    public Cursor selectRecords() {
        String[] cols = new String[] {EMP_ID, EMP_NAME};  
        Cursor mCursor = database.query(true, EMP_TABLE,cols,null  
            , null, null, null, null, null);  
        if (mCursor != null) {  
            mCursor.moveToFirst();  
        }  
        return mCursor; // iterate to get each value.
    }
}

Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.

How do I update a model value in JavaScript in a Razor view?

You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.

It would look something like this:

function updatePostID(val, comment)
{

    var args = {};
    args.PostID = val;
    args.Comment = comment;

    $.ajax({
     type: "POST",
     url: controllerActionMethodUrlHere,
     contentType: "application/json; charset=utf-8",
     data: args,
     dataType: "json",
     success: function(msg) 
     {
        // Something afterwards here

     }
    });

}

NumPy array initialization (fill with identical values)

You can use numpy.tile, e.g. :

v = 7
rows = 3
cols = 5
a = numpy.tile(v, (rows,cols))
a
Out[1]: 
array([[7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7]])

Although tile is meant to 'tile' an array (instead of a scalar, as in this case), it will do the job, creating pre-filled arrays of any size and dimension.

What does the following Oracle error mean: invalid column index

I had this problem in one legacy application that create prepared statement dynamically.

String firstName;
StringBuilder query =new StringBuilder("select id, name from employee where country_Code=1");
query.append("and  name like '");
query.append(firstName + "' ");
query.append("and ssn=?");
PreparedStatement preparedStatement =new prepareStatement(query.toString());

when it try to set value for ssn, it was giving invalid column index error, and finally found out that it is caused by firstName having ' within; that disturb the syntax.

How can I make all images of different height and width the same via CSS?

I was looking for a solution for this same problem, to create a list of logos.

I came up with this solution that uses a bit of flexbox, which works for us since we're not worried about old browsers.

This example assumes a 100x100px box but I'm pretty sure the size could be flexible/responsive.

.img__container {
    display: flex;
    padding: 15px 12px;
    box-sizing: border-box;
    width: 100px; height: 100px;

    img {
        margin: auto;
        max-width: 100%;
        max-height: 100%;
    }
}

ps.: you may need to add some prefixes or use autoprefixer.

jQuery, checkboxes and .is(":checked")

$( "#checkbox" ).change(function() {
    if($(this).is(":checked")){
        alert('hi');
    }

});

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

How to implement the Softmax function in Python

Goal was to achieve similar results using Numpy and Tensorflow. The only change from original answer is axis parameter for np.sum api.

Initial approach : axis=0 - This however does not provide intended results when dimensions are N.

Modified approach: axis=len(e_x.shape)-1 - Always sum on the last dimension. This provides similar results as tensorflow's softmax function.

def softmax_fn(input_array):
    """
    | **@author**: Prathyush SP
    |
    | Calculate Softmax for a given array
    :param input_array: Input Array
    :return: Softmax Score
    """
    e_x = np.exp(input_array - np.max(input_array))
    return e_x / e_x.sum(axis=len(e_x.shape)-1)

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

I had this problem after installing Crystal Reports for Visual Studio. I solved it by closing all Visual Studio instances and reinstalling Crystal Reports.

Populating a database in a Laravel migration file

If you already have filled columns and have added new one or you want to fill out old column with new mock values , do this:

public function up()
{
    DB::table('foydabars')->update(
        array(
            'status' => '0'
        )
    );
}

custom facebook share button

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

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

So when you want to share something

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

And finally JS to handle click:

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

return false;
});

How to manually update datatables table with new JSON data

SOLUTION: (Notice: this solution is for datatables version 1.10.4 (at the moment) not legacy version).

CLARIFICATION Per the API documentation (1.10.15), the API can be accessed three ways:

  1. The modern definition of DataTables (upper camel case):

    var datatable = $( selector ).DataTable();

  2. The legacy definition of DataTables (lower camel case):

    var datatable = $( selector ).dataTable().api();

  3. Using the new syntax.

    var datatable = new $.fn.dataTable.Api( selector );

Then load the data like so:

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Use draw(false) to stay on the same page after the data update.

API references:

https://datatables.net/reference/api/clear()

https://datatables.net/reference/api/rows.add()

https://datatables.net/reference/api/draw()

How do I store and retrieve a blob from sqlite?

In C++ (without error checking):

std::string blob = ...; // assume blob is in the string


std::string query = "INSERT INTO foo (blob_column) VALUES (?);";

sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, query, query.size(), &stmt, nullptr);
sqlite3_bind_blob(stmt, 1, blob.data(), blob.size(), 
                  SQLITE_TRANSIENT);

That can be SQLITE_STATIC if the query will be executed before blob gets destructed.

How to zip a whole folder using PHP

For anyone reading this post and looking for a why to zip the files using addFile instead of addFromString, that does not zip the files with their absolute path (just zips the files and nothing else), see my question and answer here

What exactly is OAuth (Open Authorization)?

OAuth happened when we sign up SO account with Facebook/ Google button.

  1. Application (SO) redirecting user to the provider's authorization URL. ( Displaying a web page asking the user if he or she wishes to grant the application access to read and update their data).
  2. User agree to grant the application process.
  3. Service provider redirects user back to application (SO), passing authorization code as parameter.
  4. SO exchanges the code for an access grant.

Source : OAuth1 service providers

How to hide a button programmatically?

Kotlin code is a lot simpler:

if(isVisable) {
    clearButton.visibility = View.INVISIBLE
}
else {
    clearButton.visibility = View.VISIBLE
}

How to import cv2 in python3?

Your screenshot shows you doing a pip install from the python terminal which is wrong. Do that outside the python terminal. Also the package I believe you want is:

pip install opencv-python

Since you're running on Windows, I might look at the official install manual: https://breakthrough.github.io/Installing-OpenCV

opencv2 is ONLY compatible with Python3 if you do so by compiling the source code. See the section under opencv supported python versions: https://pypi.org/project/opencv-python

How to create query parameters in Javascript?

If you are using Prototype there is Form.serialize

If you are using jQuery there is Ajax/serialize

I do not know of any independent functions to accomplish this, though, but a google search for it turned up some promising options if you aren't currently using a library. If you're not, though, you really should because they are heaven.

jQuery Datepicker localization

You can do like this

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

Changing the color of a clicked table row using jQuery

To change color of a cell:

$(document).on('click', '#table tbody td', function (event) {


    var selected = $(this).hasClass("obstacle");
    $("#table tbody td").removeClass("obstacle");
    if (!selected)
        $(this).addClass("obstacle");

});

Git ignore local file changes

git pull wants you to either remove or save your current work so that the merge it triggers doesn't cause conflicts with your uncommitted work. Note that you should only need to remove/save untracked files if the changes you're pulling create files in the same locations as your local uncommitted files.

Remove your uncommitted changes

Tracked files

git checkout -f

Untracked files

git clean -fd

Save your changes for later

Tracked files

git stash

Tracked files and untracked files

git stash -u

Reapply your latest stash after git pull:

git stash pop

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

You just need to enter this command:

sudo apt-get install gcc

Get The Current Domain Name With Javascript (Not the path, etc.)

window.location.hostname is a good start. But it includes sub-domains, which you probably want to remove. E.g. if the hostname is www.example.com, you probably want just the example.com bit.

There are, as ever, corner cases that make this fiddly, e.g. bbc.co.uk. The following regex works well for me:

_x000D_
_x000D_
let hostname = window.location.hostname;
// remove any subdomains, e.g. www.example.com -> example.com
let domain = hostname.match(/^(?:.*?\.)?(\w{3,}\.(?:\w{2,8}|\w{2,4}\.\w{2,4}))$/)[1];
console.log("domain: ", domain);
_x000D_
_x000D_
_x000D_

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

You could set width of div using Javascript and add white-space:pre-wrap to p tag, this break your textarea content at end of each line.

_x000D_
_x000D_
document.querySelector("button").onclick = function gt(){_x000D_
var card = document.createElement('div');_x000D_
card.style.width = "160px";_x000D_
card.style.background = "#eee";_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.style.whiteSpace = "pre-wrap";_x000D_
card.append(post);_x000D_
post.append(postText);_x000D_
document.body.append(card);_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required>_x000D_
Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea>_x000D_
<br><br>_x000D_
<button>Copy!!</button>
_x000D_
_x000D_
_x000D_

SQL Server query - Selecting COUNT(*) with DISTINCT

SELECT COUNT(DISTINCT program_name) AS Count, program_type AS [Type] 
FROM cm_production 
WHERE push_number=@push_number 
GROUP BY program_type

How to print a specific row of a pandas DataFrame?

If you want to display at row=159220

row=159220

#To display in a table format
display(res.loc[row:row])
display(res.iloc[row:row+1])

#To display in print format
display(res.loc[row])
display(res.iloc[row])

How to set a value to a file input in HTML?

You can't. And it's a security measure. Imagine if someone writes JS that sets file input value to some sensitive data file?

Why can't I use the 'await' operator within the body of a lock statement?

Basically it would be the wrong thing to do.

There are two ways this could be implemented:

  • Keep hold of the lock, only releasing it at the end of the block.
    This is a really bad idea as you don't know how long the asynchronous operation is going to take. You should only hold locks for minimal amounts of time. It's also potentially impossible, as a thread owns a lock, not a method - and you may not even execute the rest of the asynchronous method on the same thread (depending on the task scheduler).

  • Release the lock in the await, and reacquire it when the await returns
    This violates the principle of least astonishment IMO, where the asynchronous method should behave as closely as possible like the equivalent synchronous code - unless you use Monitor.Wait in a lock block, you expect to own the lock for the duration of the block.

So basically there are two competing requirements here - you shouldn't be trying to do the first here, and if you want to take the second approach you can make the code much clearer by having two separated lock blocks separated by the await expression:

// Now it's clear where the locks will be acquired and released
lock (foo)
{
}
var result = await something;
lock (foo)
{
}

So by prohibiting you from awaiting in the lock block itself, the language is forcing you to think about what you really want to do, and making that choice clearer in the code that you write.

Android Studio is slow (how to speed up)?

  • I should mention that if you are using Mac, downloading and running an app from the App Store (like "iBoostUp" etc.) which will clean out unused system files can speed up your computer dramatically, including AS.

  • I also found that adding more memory to my Mac sped up AS as well.

MSSQL Error 'The underlying provider failed on Open'

Defining a new Windows Firewall rule for SQL Server (and for port 1433) on the server machine solves this error (if your servername, user login name or password is not wrong in your connection string...).

Handle spring security authentication exceptions with @ExceptionHandler

Update: If you like and prefer to see the code directly, then I have two examples for you, one using standard Spring Security which is what you are looking for, the other one is using the equivalent of Reactive Web and Reactive Security:
- Normal Web + Jwt Security
- Reactive Jwt

The one that I always use for my JSON based endpoints looks like the following:

@Component
public class JwtAuthEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    ObjectMapper mapper;

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException e)
            throws IOException, ServletException {
        // Called when the user tries to access an endpoint which requires to be authenticated
        // we just return unauthorizaed
        logger.error("Unauthorized error. Message - {}", e.getMessage());

        ServletServerHttpResponse res = new ServletServerHttpResponse(response);
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        res.getServletResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        res.getBody().write(mapper.writeValueAsString(new ErrorResponse("You must authenticated")).getBytes());
    }
}

The object mapper becomes a bean once you add the spring web starter, but I prefer to customize it, so here is my implementation for ObjectMapper:

  @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.modules(new JavaTimeModule());

        // for example: Use created_at instead of createdAt
        builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

        // skip null fields
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return builder;
    }

The default AuthenticationEntryPoint you set in your WebSecurityConfigurerAdapter class:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ............
   @Autowired
    private JwtAuthEntryPoint unauthorizedHandler;
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                // .antMatchers("/api/auth**", "/api/login**", "**").permitAll()
                .anyRequest().permitAll()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        http.headers().frameOptions().disable(); // otherwise H2 console is not available
        // There are many ways to ways of placing our Filter in a position in the chain
        // You can troubleshoot any error enabling debug(see below), it will print the chain of Filters
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
// ..........
}

How can I prevent the backspace key from navigating back?

JavaScript - jQuery way:

$(document).on("keydown", function (e) {
    if (e.which === 8 && !$(e.target).is("input, textarea")) {
        e.preventDefault();
    }
});

Javascript - the native way, that works for me:

<script type="text/javascript">

//on backspace down + optional callback
function onBackspace(e, callback){
    var key;
    if(typeof e.keyIdentifier !== "undefined"){
        key = e.keyIdentifier;

    }else if(typeof e.keyCode !== "undefined"){
        key = e.keyCode;
    }
    if (key === 'U+0008' || 
        key === 'Backspace' || 
        key === 8) {
                    if(typeof callback === "function"){
                callback();
            }
            return true;
        }
    return false;
}

//event listener
window.addEventListener('keydown', function (e) {

    switch(e.target.tagName.toLowerCase()){
        case "input":
        case "textarea":
        break;
        case "body":
            onBackspace(e,function(){
                e.preventDefault();
            });

        break;
    }
}, true);
</script>

Should I use window.navigate or document.location in JavaScript?

window.location will affect to your browser target. document.location will only affect to your browser and frame/iframe.

Difference between "or" and || in Ruby?

The way I use these operators:

||, && are for boolean logic. or, and are for control flow. E.g.

do_smth if may_be || may_be -- we evaluate the condition here

do_smth or do_smth_else -- we define the workflow, which is equivalent to do_smth_else unless do_smth

to give a simple example:

> puts "a" && "b"
b

> puts 'a' and 'b'
a

A well-known idiom in Rails is render and return. It's a shortcut for saying return if render, while render && return won't work. See "Avoiding Double Render Errors" in the Rails documentation for more information.

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

In php, is 0 treated as empty?

In case of numeric values you should use is_numeric function:

$var = 0;

if (is_numeric($var))
{
  echo "Its not empty";
} 
else 
{
    echo "Its empty";
}

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

How do you kill all current connections to a SQL Server 2005 database?

I use sp_who to get list of all process in database. This is better because you may want to review which process to kill.

declare @proc table(
    SPID bigint,
    Status nvarchar(255),
    Login nvarchar(255),
    HostName nvarchar(255),
    BlkBy nvarchar(255),
    DBName nvarchar(255),
    Command nvarchar(MAX),
    CPUTime bigint,
    DiskIO bigint,
    LastBatch nvarchar(255),
    ProgramName nvarchar(255),
    SPID2 bigint,
    REQUESTID bigint
)

insert into @proc
exec sp_who2

select  *, KillCommand = concat('kill ', SPID, ';')
from    @proc

Result
You can use command in KillCommand column to kill the process you want to.

SPID    KillCommand
26      kill 26;
27      kill 27;
28      kill 28;

What is the difference between a database and a data warehouse?

Data Warehouse vs Database: A data warehouse is specially designed for data analytics, which involves reading large amounts of data to understand relationships and trends across the data. A database is used to capture and store data, such as recording details of a transaction.

Data Warehouse: Suitable workloads - Analytics, reporting, big data. Data source - Data collected and normalized from many sources. Data capture - Bulk write operations typically on a predetermined batch schedule. Data normalization - Denormalized schemas, such as the Star schema or Snowflake schema. Data storage - Optimized for simplicity of access and high-speed query. performance using columnar storage. Data access - Optimized to minimize I/O and maximize data throughput.

Transactional Database: Suitable workloads - Transaction processing. Data source - Data captured as-is from a single source, such as a transactional system. Data capture - Optimized for continuous write operations as new data is available to maximize transaction throughput. Data normalization - Highly normalized, static schemas. Data storage - Optimized for high throughout write operations to a single row-oriented physical block. Data access - High volumes of small read operations.

What is the best alternative IDE to Visual Studio

The other great thing about SharpDevelop is the ability to translate solutions between the two big managed .NET languages VB.NET and C#. I believe it doesn't work for "websites" but it does for web application projects.

Printing long int value in C

To take input " long int " and output " long int " in C is :

long int n;
scanf("%ld", &n);
printf("%ld", n);

To take input " long long int " and output " long long int " in C is :

long long int n;
scanf("%lld", &n);
printf("%lld", n);

Hope you've cleared..

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

For the equivalent of NVL() and ISNULL() use:

IFNULL(column, altValue)

column : The column you are evaluating.

altValue : The value you want to return if 'column' is null.

Example:

SELECT IFNULL(middle_name, 'N/A') FROM person;

*Note: The COALESCE() function works the same as it does for other databases.

Sources:

Load image from resources area of project in C#

In my case -- I was using Icons in my resource, but I needed to add them dynamically as Images to some ToolStripMenuItem(s). So in the method that I created (which is where the code snippet below comes from), I had to convert the icon resources to bitmaps before I could return them for addition to my MenuItem.

string imageName = myImageNameStr;
imageName = imageName.Replace(" ", "_");
Icon myIcon = (Icon)Resources.ResourceManager.GetObject(imageName);
return myIcon.ToBitmap();

Something else to be aware of, if your image/icon has spaces (" ") in its name when you add them to your resource, VS will automatically replace those spaces with "_"(s). Because, spaces are not a valid character when naming your resource. Which is why I'm using the Replace() method in my referenced code. You can likely just ignore that line.

Setting custom UITableViewCells height

To have the dynamic cell height as the text of Label increases, you first need to calculate height,that the text gonna use in -heightForRowAtIndexPath delegate method and return it with the added heights of other lables,images (max height of text+height of other static componenets) and use same height in cell creation.

#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f  
#define CELL_CONTENT_MARGIN 10.0f

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{

    if (indexPath.row == 2) {  // the cell you want to be dynamic

        NSString *text = dynamic text for your label;

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        CGFloat height = MAX(size.height, 44.0f);

        return height + (CELL_CONTENT_MARGIN * 2);
    }
    else {
        return 44; // return normal cell height
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UILabel *label;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
    }

    label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 280, 34)];

    [label setNumberOfLines:2];

    label.backgroundColor = [UIColor clearColor];

    [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];

    label.adjustsFontSizeToFitWidth = NO;

    [[cell contentView] addSubview:label];


    NSString *text = dynamic text fro your label;

    [label setText:text];

    if (indexPath.row == 2) {// the cell which needs to be dynamic 

        [label setNumberOfLines:0];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];

    }
    return  cell;
}

What is the difference between Promises and Observables?

Promise

A Promise handles a single event when an async operation completes or fails.

Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.

Observable

An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event.

Illegal mix of collations error in MySql

  • Check that your users.gender column is an INTEGER.
  • Try: alter table users convert to character set latin1 collate latin1_swedish_ci;

How can I get the username of the logged-in user in Django?

request.user.get_username() or request.user.username, former is preferred.

Django docs say:

Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.

P.S. For templates, use {{ user.get_username }}