Programs & Examples On #Anonymous objects

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Redis command to get all available keys?

You can simply connect to your redis server using redis-cli, select your database and type KEYS *, please remember it will give you all the keys present in selected redis database.

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

Echo tab characters in bash script

Use printf, not echo.

There are multiple different versions of the echo command. There's /bin/echo (which may or may not be the GNU Coreutils version, depending on the system), and the echo command is built into most shells. Different versions have different ways (or no way) to specify or disable escapes for control characters.

printf, on the other hand, has much less variation. It can exist as a command, typically /bin/printf, and it's built into some shells (bash and zsh have it, tcsh and ksh don't), but the various versions are much more similar to each other than the different versions of echo are. And you don't have to remember command-line options (with a few exceptions; GNU Coreutils printf accepts --version and --help, and the built-in bash printf accepts -v var to store the output in a variable).

For your example:

res='           'x # res = "\t\tx"
printf '%s\n' "[$res]"

And now it's time for me to admit that echo will work just as well for the example you're asking about; you just need to put double quotes around the argument:

echo "[$res]"

as kmkaplan wrote (two and a half years ago, I just noticed!). The problem with your original commands:

res='           'x # res = "\t\tx"
echo '['$res']' # expect [\t\tx]

isn't with echo; it's that the shell replaced the tab with a space before echo ever saw it.

echo is fine for simple output, like echo hello world, but you should use printf whenever you want to do something more complex. You can get echo to work, but the resulting code is likely to fail when you run it with a different echo implementation or a different shell.

Turning off auto indent when pasting text into vim

I usually use :r! cat and then paste ( shift + insert ) the content, and CTRL+D.

No need to enable & disable, direct usage.

Iterate through DataSet

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}

How can I find an element by CSS class with XPath?

The ONLY right way to do it with XPath :

//div[contains(concat(" ", normalize-space(@class), " "), " Test ")]

The function normalize-space strips leading and trailing whitespace, and also replaces sequences of whitespace characters by a single space.


Note

If not need many of these Xpath queries, you might want to use a library that converts CSS selectors to XPath, as CSS selectors are usually a lot easier to both read and write than XPath queries. For example, in this case, you could use both div[class~="Test"] and div.Test to get the same result.

Some libraries I've been able to find :

How to multiply duration by integer?

It's nice that Go has a Duration type -- having explicitly defined units can prevent real-world problems.

And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.

/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
    return time.Duration(factor) * d        // method 1 -- multiply in 'Duration'
 // return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}

The official documentation demonstrates using method #1:

To convert an integer number of units to a Duration, multiply:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).

By the way, the int64 representation of Duration in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration, like int64, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292, and that's exactly how it is implemented:

// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64

So, because we know that the underlying representation of Duration is an int64, performing the cast between int64 and Duration is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.

If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.

Pass Javascript Array -> PHP

So use the client-side loop to build a two-dimensional array of your arrays, and send the entire thing to PHP in one request.

Server-side, you'll need to have another loop which does its regular insert/update for each sub-array.

Call fragment from fragment

I think now Fragment nesting is available just update the back computability jar

now lets dig in the problem it self .

public void onClick2(View view) {
    Fragment2 fragment2 = new Fragment2();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment1, fragment2);
    fragmentTransaction.commit();
}

I think the R.id.fragment1 belongs to a TextView which is not a good place to include child views in because its not a ViewGroup, you can remove the textView from the xml and replace it with a LinearLayout lets say and it will work , if not tell me what the error .

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:orientation="vertical" >

<LinearLayout 
    android:id="@+id/fragment1"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    />

<Button 
    android:id="@+id/btn_frag2"
    android:text="Call Fragment 2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

Update for the error in the comment

public class Fragment1 extends Fragment implements OnClickListener{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment1, container, false);
((Button) v.findViewById(R.id.btn_frag2)).setOnClickListener(this);
    return v;
}

public void onClick(View view) {
    Fragment2 fragment2 = new Fragment2();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction =        fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, fragment2);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

}

CSS text-overflow in a table cell?

This worked in my case, in both Firefox and Chrome:

td {
  max-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

How to find out which processes are using swap space in Linux?

Yet two more variants:

Because top or htop could be not installed on small systems, browsing /proc stay always possible.

Even on small systems, you will found a shell...

A variant! (Not bash only)

This is exactly same than lolotux script, but without any fork to grep, awk or ps. This is a lot quicker!

And as is one of the poorest regarding performance, a little work was done to ensure this script will run well under , and some other. Then, (thanks to Stéphane Chazelas,) become a lot quicker again!

#!/bin/sh 
# Get current swap usage for all running processes
# Felix Hauri 2016-08-05
# Rewritted without fork. Inspired by first stuff from
# Erik Ljungstrom 27/05/2011
# Modified by Mikko Rantalainen 2012-08-09
# Pipe the output to "sort -nk3" to get sorted output
# Modified by Marc Methot 2014-09-18
# removed the need for sudo

OVERALL=0
rifs=`printf ': \t'`
for FILE in /proc/[0-9]*/status ;do
    SUM=0
    while IFS="$rifs" read FIELD VALUE ;do
        case $FIELD in
            Pid )    PID=$VALUE      ;;
            Name )   PROGNAME="$VALUE" ;;
            VmSwap ) SUM=$((SUM=${VALUE% *}))  ;;
        esac
    done <$FILE
    [ $SUM -gt 0 ] &&
        printf "PID: %9d  swapped: %11d KB (%s)\n" $PID $SUM "$PROGNAME"
    OVERALL=$((OVERALL+SUM))
done
printf "Total swapped memory: %14u KB\n" $OVERALL

Don't forgot to double quote "$PROGNAME" ! See Stéphane Chazelas's comment:

read FIELD PROGNAME < <(
    perl -ne 'BEGIN{$0="/*/*/../../*/*"} print if /^Name/' /proc/self/status
)
echo $FIELD "$PROGNAME"

Don't try echo $PROGNAME without double quote on sensible system, and be ready to kill current shell before!

And a version

As this become a not so simple script, time is comming to write a dedicated tool by using more efficient language.

#!/usr/bin/perl -w

use strict;
use Getopt::Std;
my ($tot,$mtot)=(0,0);
my %procs;

my %opts;
getopt('', \%opts);

sub sortres {
    return $a <=> $b                                          if $opts{'p'};
    return $procs{$a}->{'cmd'} cmp $procs{$b}->{'cmd'}        if $opts{'c'};
    return $procs{$a}->{'mswap'} <=> $procs{$b}->{'mswap'}    if $opts{'m'};
    return $procs{$a}->{'swap'} <=> $procs{$b}->{'swap'};
};

opendir my $dh,"/proc";

for my $pid (grep {/^\d+$/} readdir $dh) {
    if (open my $fh,"</proc/$pid/status") {
        my ($sum,$nam)=(0,"");
        while (<$fh>) {
            $sum+=$1 if /^VmSwap:\s+(\d+)\s/;
            $nam=$1 if /^Name:\s+(\S+)/;
        }
        if ($sum) {
            $tot+=$sum;
            $procs{$pid}->{'swap'}=$sum;
            $procs{$pid}->{'cmd'}=$nam;
            close $fh;
            if (open my $fh,"</proc/$pid/smaps") {
                $sum=0;
                while (<$fh>) {
                    $sum+=$1 if /^Swap:\s+(\d+)\s/;
                };
            };
            $mtot+=$sum;
            $procs{$pid}->{'mswap'}=$sum;
        } else { close $fh; };
    };
};
map {
    printf "PID: %9d  swapped: %11d (%11d) KB (%s)\n",
        $_, $procs{$_}->{'swap'}, $procs{$_}->{'mswap'}, $procs{$_}->{'cmd'};
} sort sortres keys %procs;
printf "Total swapped memory: %14u (%11u) KB\n", $tot,$mtot;

could by run with one of

-c  sort by command name
-p  sort by pid
-m  sort by swap values
by default, output is sorted by status's vmsize

Laravel: PDOException: could not find driver

If you can, run :

composer update

composer require doctrine/dbal

It looks like you have a missing dependency

Edit:

You might need to comment out the following in your php.ini file.

;extension=pdo_mysql.so

Taken from this post: Laravel 5 PDOException Could Not Find Driver . I think I had to do something exactly like this when setting up laravel on digital ocean.

How to run a task when variable is undefined in ansible?

Strictly stated you must check all of the following: defined, not empty AND not None.

For "normal" variables it makes a difference if defined and set or not set. See foo and bar in the example below. Both are defined but only foo is set.

On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz and xyz.msg in the example below:

cat > test.yml <<EOF
- hosts: 127.0.0.1

  vars:
    foo: ""          # foo is defined and foo == '' and foo != None
    bar:             # bar is defined and bar != '' and bar == None

  tasks:

  - debug:
      msg : ""
    register: xyz    # xyz is defined and xyz != '' and xyz != None
                     # xyz.msg is defined and xyz.msg == '' and xyz.msg != None

  - debug:
      msg: "foo is defined and foo == '' and foo != None"
    when: foo is defined and foo == '' and foo != None

  - debug:
      msg: "bar is defined and bar != '' and bar == None"
    when: bar is defined and bar != '' and bar == None

  - debug:
      msg: "xyz is defined and xyz != '' and xyz != None"
    when: xyz is defined and xyz != '' and xyz != None
  - debug:
      msg: "{{ xyz }}"

  - debug:
      msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
    when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
  - debug:
      msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml

Insert a row to pandas dataframe

You can simply append the row to the end of the DataFrame, and then adjust the index.

For instance:

df = df.append(pd.DataFrame([[2,3,4]],columns=df.columns),ignore_index=True)
df.index = (df.index + 1) % len(df)
df = df.sort_index()

Or use concat as:

df = pd.concat([pd.DataFrame([[1,2,3,4,5,6]],columns=df.columns),df],ignore_index=True)

How can I check if an argument is defined when starting/calling a batch file?

A more-advanced example:

? unlimited arguments.

? exist on file system (either file or directory?) or a generic string.

? specify if is a file

? specify is a directory

? no extensions, would work in legacy scripts!

? minimal code ?

@echo off

:loop
      ::-------------------------- has argument ?
      if ["%~1"]==[""] (
        echo done.
        goto end
      )
      ::-------------------------- argument exist ?
      if not exist %~s1 (
        echo not exist
      ) else (
        echo exist
        if exist %~s1\NUL (
          echo is a directory
        ) else (
          echo is a file
        )
      )
      ::--------------------------
      shift
      goto loop
      
      
:end

pause

? other stuff..?

¦ in %~1 - the ~ removes any wrapping " or '.

¦ in %~s1 - the s makes the path be DOS 8.3 naming, which is a nice trick to avoid spaces in file-name while checking stuff (and this way no need to wrap the resource with more "s.

¦ the ["%~1"]==[""] "can not be sure" if the argument is a file/directory or just a generic string yet, so instead the expression uses brackets and the original unmodified %1 (just without the " wrapping, if any..)

if there were no arguments of if we've used shift and the arg-list pointer has passed the last one, the expression will be evaluated to [""]==[""].

¦ this is as much specific you can be without using more tricks (it would work even in windows-95's batch-scripts...)

¦ execution examples

save it as identifier.cmd

it can identify an unlimited arguments (normally you are limited to %1-%9), just remember to wrap the arguments with inverted-commas, or use 8.3 naming, or drag&drop them over (it automatically does either of above).


this allows you to run the following commands:

?identifier.cmd c:\windows and to get

exist
is a directory
done

?identifier.cmd "c:\Program Files (x86)\Microsoft Office\OFFICE11\WINWORD.EXE" and to get

exist
is a file
done

? and multiple arguments (of course this is the whole-deal..)

identifier.cmd c:\windows\system32 c:\hiberfil.sys "c:\pagefile.sys" hello-world

and to get

exist
is a directory
exist
is a file
exist
is a file
not exist
done.

naturally it can be a lot more complex, but nice examples should always be simple and minimal. :)

Hope it helps anyone :)

published here:CMD Ninja - Unlimited Arguments Processing, Identifying If Exist In File-System, Identifying If File Or Directory

and here is a working example that takes any amount of APK files (Android apps) and installs them on your device via debug-console (ADB.exe): Make The Previous Post A Mass APK Installer That Does Not Uses ADB Install-Multi Syntax

How to while loop until the end of a file in Python without checking for empty line?

Find end position of file:

f = open("file.txt","r")
f.seek(0,2) #Jumps to the end
f.tell()    #Give you the end location (characters from start)
f.seek(0)   #Jump to the beginning of the file again

Then you can to:

if line == '' and f.tell() == endLocation:
   break

Change UITableView height dynamically

create your cell by xib or storyboard. give it's outlet's contents. now call it in CellForRowAtIndexPath. eg. if you want to set cell height according to Comment's label text. enter image description here

so set you commentsLbl.numberOfLine=0;enter image description here

so set you commentsLbl.numberOfLine=0;

then in ViewDidLoad

 self.table.estimatedRowHeight = 44.0 ;
self.table.rowHeight = UITableViewAutomaticDimension;

and now

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;}

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Use this code ,which helped me to open all types of files ...

 private void openFile(File url) {

    try {

        Uri uri = Uri.fromFile(url);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
            // Word document
            intent.setDataAndType(uri, "application/msword");
        } else if (url.toString().contains(".pdf")) {
            // PDF file
            intent.setDataAndType(uri, "application/pdf");
        } else if (url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
            // Powerpoint file
            intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
        } else if (url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
            // Excel file
            intent.setDataAndType(uri, "application/vnd.ms-excel");
        } else if (url.toString().contains(".zip")) {
            // ZIP file
            intent.setDataAndType(uri, "application/zip");
        } else if (url.toString().contains(".rar")){
            // RAR file
            intent.setDataAndType(uri, "application/x-rar-compressed");
        } else if (url.toString().contains(".rtf")) {
            // RTF file
            intent.setDataAndType(uri, "application/rtf");
        } else if (url.toString().contains(".wav") || url.toString().contains(".mp3")) {
            // WAV audio file
            intent.setDataAndType(uri, "audio/x-wav");
        } else if (url.toString().contains(".gif")) {
            // GIF file
            intent.setDataAndType(uri, "image/gif");
        } else if (url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
            // JPG file
            intent.setDataAndType(uri, "image/jpeg");
        } else if (url.toString().contains(".txt")) {
            // Text file
            intent.setDataAndType(uri, "text/plain");
        } else if (url.toString().contains(".3gp") || url.toString().contains(".mpg") ||
                url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
            // Video files
            intent.setDataAndType(uri, "video/*");
        } else {
            intent.setDataAndType(uri, "*/*");
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, "No application found which can open the file", Toast.LENGTH_SHORT).show();
    }
}

How do I validate a date string format in python?

From mere curiosity, I timed the two rivalling answers posted above.
And I had the following results:

dateutil.parser (valid str): 4.6732222699938575
dateutil.parser (invalid str): 1.7270505399937974
datetime.strptime (valid): 0.7822393209935399
datetime.strptime (invalid): 0.4394566189876059

And here's the code I used (Python 3.6)


from dateutil import parser as date_parser
from datetime import datetime
from timeit import timeit


def is_date_parsing(date_str):
    try:
        return bool(date_parser.parse(date_str))
    except ValueError:
        return False


def is_date_matching(date_str):
    try:
        return bool(datetime.strptime(date_str, '%Y-%m-%d'))
    except ValueError:
        return False



if __name__ == '__main__':
    print("dateutil.parser (valid date):", end=' ')
    print(timeit("is_date_parsing('2021-01-26')",
                 setup="from __main__ import is_date_parsing",
                 number=100000))

    print("dateutil.parser (invalid date):", end=' ')
    print(timeit("is_date_parsing('meh')",
                 setup="from __main__ import is_date_parsing",
                 number=100000))

    print("datetime.strptime (valid date):", end=' ')
    print(timeit("is_date_matching('2021-01-26')",
                 setup="from __main__ import is_date_matching",
                 number=100000))

    print("datetime.strptime (invalid date):", end=' ')
    print(timeit("is_date_matching('meh')",
                 setup="from __main__ import is_date_matching",
                 number=100000))

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

php error: Class 'Imagick' not found

Debian 9

I just did the following and everything else needed got automatically installed as well.

sudo apt-get -y -f install php-imagick
sudo /etc/init.d/apache2 restart

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I am adding few more understanding.

  1. Cursor is only about a statement objecct; It is neither resultSet nor the connection object.
  2. But still we have to close the resultset to free some oracle memory. Still if you don't close the resultset that won't be counted for CURSORS.
  3. Closing Statement object will automatically close resultset object too.
  4. Cursor will be created for all the SELECT/INSERT/UPDATE/DELETE statement.
  5. Each ORACLE DB instance can be identified using oracle SID; similarly ORACLE DB can identify each connection using connection SID. Both SID are different.
  6. So ORACLE session is nothing but a jdbc(tcp) connection; which is nothing but one SID.
  7. If we set maximum cursors as 500 then it is only for one JDBC session/connection/SID.
  8. So we can have many JDBC connection with its respective no of cursors (statements).
  9. Once the JVM is terminated all the connections/cursors will be closed, OR JDBCConnection is closed CURSORS with respect to that connection will be closed.

Loggin as sysdba.

In Putty (Oracle login):

  [oracle@db01 ~]$ sqlplus / as sysdba

In SqlPlus:

UserName: sys as sysdba

Set session_cached_cursors value to 0 so that it wont have closed cursors.

 alter session set session_cached_cursors=0
 select * from V$PARAMETER where name='session_cached_cursors'

Select existing OPEN_CURSORS valuse set per connection in DB

 SELECT max(a.value) as highest_open_cur, p.value as max_open_cur FROM v$sesstat a, v$statname b, v$parameter p WHERE a.statistic# = b.statistic# AND b.name = 'opened cursors current' AND p.name= 'open_cursors'  GROUP BY p.value;

Below is the query to find the SID/connections list with open cursor values.

 SELECT a.value, s.username, s.sid, s.serial#
 FROM v$sesstat a, v$statname b, v$session s
 WHERE a.statistic# = b.statistic#  AND s.sid=a.sid 
 AND b.name = 'opened cursors current' AND username = 'SCHEMA_NAME_IN_CAPS'

Use the below query to identify the sql's in the open cursors

 SELECT oc.sql_text, s.sid 
 FROM v$open_cursor oc, v$session s
 WHERE OC.sid = S.sid
 AND s.sid=1604
 AND OC.USER_NAME ='SCHEMA_NAME_IN_CAPS'

Now debug the Code and Enjoy!!! :)

How do I use hexadecimal color strings in Flutter?

The Color class expects an ARGB integer. Since you try to use it with RGB value, represent it as int and prefix it with 0xff.

Color mainColor = Color(0xffb74093);

If you get annoyed by this and still wish to use strings, you can extend Color and add a string constructor

class HexColor extends Color {
  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    return int.parse(hexColor, radix: 16);
  }

  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));
}

usage

Color color1 = HexColor("b74093");
Color color2 = HexColor("#b74093");
Color color3 = HexColor("#88b74093"); // if you wish to use ARGB format

Exporting PDF with jspdf not rendering CSS

jspdf does not work with css but it can work along with html2canvas. You can use jspdf along with html2canvas.

include these two files in script on your page :

<script type="text/javascript" src="html2canvas.js"></script>
  <script type="text/javascript" src="jspdf.min.js"></script>
  <script type="text/javascript">
  function genPDF()
  {
   html2canvas(document.body,{
   onrendered:function(canvas){

   var img=canvas.toDataURL("image/png");
   var doc = new jsPDF();
   doc.addImage(img,'JPEG',20,20);
   doc.save('test.pdf');
   }

   });

  }
  </script>

You need to download script files such as https://github.com/niklasvh/html2canvas/releases https://cdnjs.com/libraries/jspdf

make clickable button on page so that it will generate pdf and it will be seen same as that of original html page.

<a href="javascript:genPDF()">Download PDF</a>  

It will work perfectly.

How to update a record using sequelize for node?

Since version 2.0.0 you need to wrap your where clause in a where property:

Project.update(
  { title: 'a very different title now' },
  { where: { _id: 1 } }
)
  .success(result =>
    handleResult(result)
  )
  .error(err =>
    handleError(err)
  )

Update 2016-03-09

The latest version actually doesn't use success and error anymore but instead uses then-able promises.

So the upper code will look as follows:

Project.update(
  { title: 'a very different title now' },
  { where: { _id: 1 } }
)
  .then(result =>
    handleResult(result)
  )
  .catch(err =>
    handleError(err)
  )

Using async/await

try {
  const result = await Project.update(
    { title: 'a very different title now' },
    { where: { _id: 1 } }
  )
  handleResult(result)
} catch (err) {
  handleError(err)
}

http://docs.sequelizejs.com/en/latest/api/model/#updatevalues-options-promisearrayaffectedcount-affectedrows

How to save a list as numpy array in python?

First of all, I'd recommend you to go through NumPy's Quickstart tutorial, which will probably help with these basic questions.

You can directly create an array from a list as:

import numpy as np
a = np.array( [2,3,4] )

Or from a from a nested list in the same way:

import numpy as np
a = np.array( [[2,3,4], [3,4,5]] )

AttributeError: 'str' object has no attribute 'strftime'

you should change cr_date(str) to datetime object then you 'll change the date to the specific format:

cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")

Batch script: how to check for admin rights

Alternative: Use an external utility that is designed for this purpose, e.g., IsAdmin.exe (unrestricted freeware).

Exit codes:

0 - Current user not member of Administrators group

1 - Current user member of Administrators and running elevated

2 - Current user member of Administrators, but not running elevated

How to avoid annoying error "declared and not used"

You can use a simple "null function" for this, for example:

func Use(vals ...interface{}) {
    for _, val := range vals {
        _ = val
    }
}

Which you can use like so:

package main

func main() {
    a := "declared and not used"
    b := "another declared and not used"
    c := 123

    Use(a, b, c)
}

There's also a package for this so you don't have to define the Use function every time:

import (
  "github.com/lunux2008/xulu"
)

func main() {
  // [..]

  xulu.Use(a, b, c)
}

Changing user agent on urllib2.urlopen

All these should work in theory, but (with Python 2.7.2 on Windows at least) any time you send a custom User-agent header, urllib2 doesn't send that header. If you don't try to send a User-agent header, it sends the default Python / urllib2

None of these methods seem to work for adding User-agent but they work for other headers:

opener = urllib2.build_opener(proxy)
opener.addheaders = {'User-agent':'Custom user agent'}
urllib2.install_opener(opener)

request = urllib2.Request(url, headers={'User-agent':'Custom user agent'})

request.headers['User-agent'] = 'Custom user agent'

request.add_header('User-agent', 'Custom user agent')

if (boolean condition) in Java

boolean state = "TURNED ON";

is not a Java valid code. boolean can receive only boolean values (true or false) and "TURNED ON"is a String.

EDIT:

now you are talking about a loop and your code does not contain any. your var state is false because the boolean default value and you execute the else clause.

Command to run a .bat file

Can refer to here: https://ss64.com/nt/start.html

start "" /D F:\- Big Packets -\kitterengine\Common\ /W Template.bat

Difference between / and /* in servlet mapping url pattern

I'd like to supplement BalusC's answer with the mapping rules and an example.

Mapping rules from Servlet 2.5 specification:

  1. Map exact URL
  2. Map wildcard paths
  3. Map extensions
  4. Map to the default servlet

In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello

  1. No exact URL servlets installed, next.
  2. No wildcard paths servlets installed, next.
  3. Doesn't match any extensions, next.
  4. Map to the default servlet, return.

To map http://host:port/context/hello.jsp

  1. No exact URL servlets installed, next.
  2. No wildcard paths servlets installed, next.
  3. Found extension servlet, return.

Multiple Updates in MySQL

All of the following applies to InnoDB.

I feel knowing the speeds of the 3 different methods is important.

There are 3 methods:

  1. INSERT: INSERT with ON DUPLICATE KEY UPDATE
  2. TRANSACTION: Where you do an update for each record within a transaction
  3. CASE: In which you a case/when for each different record within an UPDATE

I just tested this, and the INSERT method was 6.7x faster for me than the TRANSACTION method. I tried on a set of both 3,000 and 30,000 rows.

The TRANSACTION method still has to run each individually query, which takes time, though it batches the results in memory, or something, while executing. The TRANSACTION method is also pretty expensive in both replication and query logs.

Even worse, the CASE method was 41.1x slower than the INSERT method w/ 30,000 records (6.1x slower than TRANSACTION). And 75x slower in MyISAM. INSERT and CASE methods broke even at ~1,000 records. Even at 100 records, the CASE method is BARELY faster.

So in general, I feel the INSERT method is both best and easiest to use. The queries are smaller and easier to read and only take up 1 query of action. This applies to both InnoDB and MyISAM.

Bonus stuff:

The solution for the INSERT non-default-field problem is to temporarily turn off the relevant SQL modes: SET SESSION sql_mode=REPLACE(REPLACE(@@SESSION.sql_mode,"STRICT_TRANS_TABLES",""),"STRICT_ALL_TABLES",""). Make sure to save the sql_mode first if you plan on reverting it.

As for other comments I've seen that say the auto_increment goes up using the INSERT method, this does seem to be the case in InnoDB, but not MyISAM.

Code to run the tests is as follows. It also outputs .SQL files to remove php interpreter overhead

<?php
//Variables
$NumRows=30000;

//These 2 functions need to be filled in
function InitSQL()
{

}
function RunSQLQuery($Q)
{

}

//Run the 3 tests
InitSQL();
for($i=0;$i<3;$i++)
    RunTest($i, $NumRows);

function RunTest($TestNum, $NumRows)
{
    $TheQueries=Array();
    $DoQuery=function($Query) use (&$TheQueries)
    {
        RunSQLQuery($Query);
        $TheQueries[]=$Query;
    };

    $TableName='Test';
    $DoQuery('DROP TABLE IF EXISTS '.$TableName);
    $DoQuery('CREATE TABLE '.$TableName.' (i1 int NOT NULL AUTO_INCREMENT, i2 int NOT NULL, primary key (i1)) ENGINE=InnoDB');
    $DoQuery('INSERT INTO '.$TableName.' (i2) VALUES ('.implode('), (', range(2, $NumRows+1)).')');

    if($TestNum==0)
    {
        $TestName='Transaction';
        $Start=microtime(true);
        $DoQuery('START TRANSACTION');
        for($i=1;$i<=$NumRows;$i++)
            $DoQuery('UPDATE '.$TableName.' SET i2='.(($i+5)*1000).' WHERE i1='.$i);
        $DoQuery('COMMIT');
    }
    
    if($TestNum==1)
    {
        $TestName='Insert';
        $Query=Array();
        for($i=1;$i<=$NumRows;$i++)
            $Query[]=sprintf("(%d,%d)", $i, (($i+5)*1000));
        $Start=microtime(true);
        $DoQuery('INSERT INTO '.$TableName.' VALUES '.implode(', ', $Query).' ON DUPLICATE KEY UPDATE i2=VALUES(i2)');
    }
    
    if($TestNum==2)
    {
        $TestName='Case';
        $Query=Array();
        for($i=1;$i<=$NumRows;$i++)
            $Query[]=sprintf('WHEN %d THEN %d', $i, (($i+5)*1000));
        $Start=microtime(true);
        $DoQuery("UPDATE $TableName SET i2=CASE i1\n".implode("\n", $Query)."\nEND\nWHERE i1 IN (".implode(',', range(1, $NumRows)).')');
    }
    
    print "$TestName: ".(microtime(true)-$Start)."<br>\n";

    file_put_contents("./$TestName.sql", implode(";\n", $TheQueries).';');
}

How to put text in the upper right, or lower right corner of a "box" using css

Float right the text you want to appear on the right, and in the markup make sure that this text and its surrounding span occurs before the text that should be on the left. If it doesn't occur first, you may have problems with the floated text appearing on a different line.

<html>
  <body>
    <div>
      <span style="float:right">here</span>Lorem Ipsum etc<br/>
      blah<br/>
      blah blah<br/>
      blah<br/>
      <span style="float:right">and here</span>lorem ipsums<br/>
    </div>
  </body>
</html>

Note that this works for any line, not just the top and bottom corners.

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

Running Bash commands in Python

Also you can use 'os.popen'. Example:

import os

command = os.popen('ls -al')
print(command.read())
print(command.close())

Output:

total 16
drwxr-xr-x 2 root root 4096 ago 13 21:53 .
drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
-rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
-rw-r--r-- 1 root root   77 ago 13 21:53 test.py

None

Configure WAMP server to send email

Sendmail wasn't working for me so I used msmtp 1.6.2 w32 and most just followed the instructions at DeveloperSide. Here is a quick rundown of the setup for posterity:

Enabled IMAP access under your Gmail account (the one msmtp is sending emails from)

Enable access for less secure apps. Log into your google account and go here

Edit php.ini, find and change each setting below to reflect the following:

; These are commented out by prefixing a semicolon
;SMTP = localhost
;smtp_port = 25

; Set these paths to where you put your msmtp files.
; I used backslashes in php.ini and it works fine.
; The example in the devside guide uses forwardslashes. 
sendmail_path = "C:\wamp64\msmtp\msmtp.exe -d -C C:\wamp64\msmtp\msmtprc.ini -t --read-envelope-from"

mail.log = "C:\wamp64\msmtp\maillog.txt"

Create and edit the file msmtprc.ini in the same directory as your msmtp.exe file as follows, replacing it with your own email and password:

# Default values for all accounts
defaults
tls_certcheck off
# I used forward slashes here and it works.
logfile C:/wamp64/msmtp/msmtplog.txt

account Gmail
host smtp.gmail.com
port 587
auth on
tls on
from [email protected]
user [email protected]
password ReplaceWithYourPassword
account default : gmail

Git - push current branch shortcut

I use such alias in my .bashrc config

alias gpb='git push origin `git rev-parse --abbrev-ref HEAD`'

On the command $gpb it takes the current branch name and pushes it to the origin.

Here are my other aliases:

alias gst='git status'
alias gbr='git branch'
alias gca='git commit -am'
alias gco='git checkout'

Add new row to excel Table (VBA)

I had the same error message and after lots of trial and error found out that it was caused by an advanced filter which was set on the ListObject. After clearing the advanced filter .listrows.add worked fine again. To clear the filter I use this - no idea how one could clear the filter only for the specific listobject instead of the complete worksheet.

Worksheets("mysheet").ShowAllData

Twitter Bootstrap Responsive Background-Image inside Div

Mby bootstrap img-responsive class is you looking for.

Convert a PHP object to an associative array

There's my proposal, if you have objects in objects with even private members:

public function dismount($object) {
    $reflectionClass = new \ReflectionClass(get_class($object));
    $array = array();
    foreach ($reflectionClass->getProperties() as $property) {
        $property->setAccessible(true);
        if (is_object($property->getValue($object))) {
            $array[$property->getName()] = $this->dismount($property->getValue($object));
        } else {
            $array[$property->getName()] = $property->getValue($object);
        }
        $property->setAccessible(false);
    }
    return $array;
}

How to increment a variable on a for loop in jinja template?

As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.

You can defeat this behavior by using an object rather than a scalar for 'count':

{% set count = [1] %}

You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):

{% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}

Django - after login, redirect user to his custom page --> mysite.com/username

A simpler approach relies on redirection from the page LOGIN_REDIRECT_URL. The key thing to realize is that the user information is automatically included in the request.

Suppose:

LOGIN_REDIRECT_URL = '/profiles/home'

and you have configured a urlpattern:

(r'^profiles/home', home),

Then, all you need to write for the view home() is:

from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required

@login_required
def home(request):
    return HttpResponseRedirect(
               reverse(NAME_OF_PROFILE_VIEW, 
                       args=[request.user.username]))

where NAME_OF_PROFILE_VIEW is the name of the callback that you are using. With django-profiles, NAME_OF_PROFILE_VIEW can be 'profiles_profile_detail'.

Creating instance list of different objects

How can I create a list without defining a class type? (<Employee>)

If I'm reading this correctly, you just want to avoid having to specify the type, correct?

In Java 7, you can do

List<Employee> list = new ArrayList<>();

but any of the other alternatives being discussed are just going to sacrifice type safety.

Is there a standard sign function (signum, sgn) in C/C++?

int sign(float n)
{     
  union { float f; std::uint32_t i; } u { n };
  return 1 - ((u.i >> 31) << 1);
}

This function assumes:

  • binary32 representation of floating point numbers
  • a compiler that make an exception about the strict aliasing rule when using a named union

Relative Paths in Javascript in an external file

JavaScript file paths

When in script, paths are relative to displayed page

to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:

Solution, which was employed on StackOverflow around Feb 2010:

<script type="text/javascript">
   var imagePath = 'http://sstatic.net/so/img/';
</script>

If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section

How do I set environment variables from Java?

Tried pushy's answer above and it worked for the most part. However, in certain circumstances, I would see this exception:

java.lang.String cannot be cast to java.lang.ProcessEnvironment$Variable

This turns out to happen when the method was called more than once, owing to the implementation of certain inner classes of ProcessEnvironment. If the setEnv(..) method is called more than once, when the keys are retrieved from the theEnvironment map, they are now strings (having been put in as strings by the first invocation of setEnv(...) ) and cannot be cast to the map's generic type, Variable, which is a private inner class of ProcessEnvironment.

A fixed version (in Scala), is below. Hopefully it isn't too difficult to carry over into Java.

def setEnv(newenv: java.util.Map[String, String]): Unit = {
  try {
    val processEnvironmentClass = JavaClass.forName("java.lang.ProcessEnvironment")
    val theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment")
    theEnvironmentField.setAccessible(true)

    val variableClass = JavaClass.forName("java.lang.ProcessEnvironment$Variable")
    val convertToVariable = variableClass.getMethod("valueOf", classOf[java.lang.String])
    convertToVariable.setAccessible(true)

    val valueClass = JavaClass.forName("java.lang.ProcessEnvironment$Value")
    val convertToValue = valueClass.getMethod("valueOf", classOf[java.lang.String])
    convertToValue.setAccessible(true)

    val sampleVariable = convertToVariable.invoke(null, "")
    val sampleValue = convertToValue.invoke(null, "")
    val env = theEnvironmentField.get(null).asInstanceOf[java.util.Map[sampleVariable.type, sampleValue.type]]
    newenv.foreach { case (k, v) => {
        val variable = convertToVariable.invoke(null, k).asInstanceOf[sampleVariable.type]
        val value = convertToValue.invoke(null, v).asInstanceOf[sampleValue.type]
        env.put(variable, value)
      }
    }

    val theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment")
    theCaseInsensitiveEnvironmentField.setAccessible(true)
    val cienv = theCaseInsensitiveEnvironmentField.get(null).asInstanceOf[java.util.Map[String, String]]
    cienv.putAll(newenv);
  }
  catch {
    case e : NoSuchFieldException => {
      try {
        val classes = classOf[java.util.Collections].getDeclaredClasses
        val env = System.getenv()
        classes foreach (cl => {
          if("java.util.Collections$UnmodifiableMap" == cl.getName) {
            val field = cl.getDeclaredField("m")
            field.setAccessible(true)
            val map = field.get(env).asInstanceOf[java.util.Map[String, String]]
            // map.clear() // Not sure why this was in the code. It means we need to set all required environment variables.
            map.putAll(newenv)
          }
        })
      } catch {
        case e2: Exception => e2.printStackTrace()
      }
    }
    case e1: Exception => e1.printStackTrace()
  }
}

How to get current relative directory of your Makefile?

THIS_DIR := $(dir $(abspath $(firstword $(MAKEFILE_LIST))))

What's the difference between SHA and AES encryption?

SHA stands for Secure Hash Algorithm while AES stands for Advanced Encryption Standard. So SHA is a suite of hashing algorithms. AES on the other hand is a cipher which is used to encrypt. SHA algorithms (SHA-1, SHA-256 etc...) will take an input and produce a digest (hash), this is typically used in a digital signing process (produce a hash of some bytes and sign with a private key).

java comparator, how to sort by integer?

One simple way is

Comparator<Dog> ageAscendingComp = ...;
Comparator<Dog> ageDescendingComp = Collections.reverseOrder(ageAscendingComp);
// then call the sort method

On a side note, Dog should really not implement Comparator. It means you have to do strange things like

Collections.sort(myList, new Dog("Rex", 4));
// ^-- why is a new dog being made? What are we even sorting by?!
Collections.sort(myList, myList.get(0));
// ^-- or perhaps more confusingly

Rather you should make Compartors as separate classes.

eg.

public class DogAgeComparator implments Comparator<Dog> {
    public int compareTo(Dog d1, Dog d2) {
        return d1.getAge() - d2.getAge();
    }
}

This has the added benefit that you can use the name of the class to say how the Comparator will sort the list. eg.

Collections.sort(someDogs, new DogNameComparator());
// now in name ascending order

Collections.sort(someDogs, Collections.reverseOrder(new DogAgeComparator()));
// now in age descending order

You should also not not have Dog implement Comparable. The Comparable interface is used to denote that there is some inherent and natural way to order these objects (such as for numbers and strings). Now this is not the case for Dog objects as sometimes you may wish to sort by age and sometimes you may wish to sort by name.

Transpose a range in VBA

Strictly in reference to prefacing "transpose", by the book, either one will work; i.e., application.transpose() OR worksheetfunction.transpose(), and by experience, if you really like typing, application.WorksheetFunction.Transpose() will work also-

Converting SVG to PNG using C#

you can use altsoft xml2pdf lib for this

getting error while updating Composer

If you're using php 7.3 for laravel 5.7. this work for me

sudo apt-get install php-gd php-xml php7.3-mbstring

How to cut first n and last n columns?

Use

cut -b COLUMN_N_BEGINS-COLUMN_N_UNTIL INPUT.TXT > OUTPUT.TXT

-f doesn't work if you have "tabs" in the text file.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I could remove the error (Run-time error '1004'. Application-defined or operation-defined error) by defining the counters as Single

Why is there no Constant feature in Java?

const in C++ does not mean that a value is a constant.

const in C++ implies that the client of a contract undertakes not to alter its value.

Whether the value of a const expression changes becomes more evident if you are in an environment which supports thread based concurrency.

As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that final has.

eg:

#include <iostream>

int main ()
{
    volatile const int x = 42;

    std::cout << x << std::endl;

    *const_cast<int*>(&x) = 7;

    std::cout << x << std::endl;

    return 0;
}

outputs 42 then 7.

Although x marked as const, as a non-const alias is created, x is not a constant. Not every compiler requires volatile for this behaviour (though every compiler is permitted to inline the constant)

With more complicated systems you get const/non-const aliases without use of const_cast, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const merely means that your code can't change it without a cast, not that the value is constant.

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Two dimensional array list

You would use

List<List<String>> listOfLists = new ArrayList<List<String>>();

And then when you needed to add a new "row", you'd add the list:

listOfLists.add(new ArrayList<String>());

I've used this mostly when I wanted to hold references to several lists of Point in a GUI so I could draw multiple curves. It works well.

For example:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class DrawStuff extends JPanel {
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private static final Color POINTS_COLOR = Color.red;
   private static final Color CURRENT_POINTS_COLOR = Color.blue;
   private static final Stroke STROKE = new BasicStroke(4f);
   private List<List<Point>> pointsList = new ArrayList<List<Point>>();
   private List<Point> currentPointList = null;

   public DrawStuff() {
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
            RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setStroke(STROKE);
      g.setColor(POINTS_COLOR);
      for (List<Point> pointList : pointsList) {
         if (pointList.size() > 1) {
            Point p1 = pointList.get(0);
            for (int i = 1; i < pointList.size(); i++) {
               Point p2 = pointList.get(i);
               int x1 = p1.x;
               int y1 = p1.y;
               int x2 = p2.x;
               int y2 = p2.y;
               g.drawLine(x1, y1, x2, y2);
               p1 = p2;
            }
         }
      }
      g.setColor(CURRENT_POINTS_COLOR);
      if (currentPointList != null && currentPointList.size() > 1) {
         Point p1 = currentPointList.get(0);
         for (int i = 1; i < currentPointList.size(); i++) {
            Point p2 = currentPointList.get(i);
            int x1 = p1.x;
            int y1 = p1.y;
            int x2 = p2.x;
            int y2 = p2.y;
            g.drawLine(x1, y1, x2, y2);
            p1 = p2;
         }
      }
   }

   private class MyMouseAdapter extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent mEvt) {
         currentPointList = new ArrayList<Point>();
         currentPointList.add(mEvt.getPoint());
         repaint();
      }

      @Override
      public void mouseDragged(MouseEvent mEvt) {
         currentPointList.add(mEvt.getPoint());
         repaint();
      }

      @Override
      public void mouseReleased(MouseEvent mEvt) {
         currentPointList.add(mEvt.getPoint());
         pointsList.add(currentPointList);
         currentPointList = null;
         repaint();
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("DrawStuff");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new DrawStuff());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

maven "cannot find symbol" message unhelpful

In my case, I was using a dependency scoped as <scope>test</scope>. This made the class available at development time but, by at compile time, I got this message.

Turn the class scope for <scope>provided</scope> solved the problem.

Find all special characters in a column in SQL Server 2008

Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'

This will give you all the row which contains any special character.

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

With IE6 / IE7 one can tweak the number of concurrent requests in the registry. Here's how to set it to four each.

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
"MaxConnectionsPerServer"=dword:00000004
"MaxConnectionsPer1_0Server"=dword:00000004

how to get the last part of a string before a certain character?

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

Demo:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'

Where is SQL Server Management Studio 2012?

I uninstalled all parts of SQL Server 2012 using Control Panel in Windows and then reinstalled (choosing "All Features"). Now it works!

How to grep Git commit diffs or contents for a certain word?

After a lot of experimentation, I can recommend the following, which shows commits that introduce or remove lines containing a given regexp, and displays the text changes in each, with colours showing words added and removed.

git log --pickaxe-regex -p --color-words -S "<regexp to search for>"

Takes a while to run though... ;-)

How to handle the new window in Selenium WebDriver using Java?

i was having some issues with windowhandle and tried this one. this one works good for me.

String parentWindowHandler = driver.getWindowHandle(); 
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
    driver.switchTo().window(subWindowHandler);

    System.out.println(subWindowHandler);
}


driver.switchTo().window(parentWindowHandler); 

how to access iFrame parent page using jquery?

yeah it works for me as well.

Note : we need to use window.parent.document

    $("button", window.parent.document).click(function()
    {
        alert("Functionality defined by def");
    });

How can I disable HREF if onclick is executed?

Simply disable default browser behaviour using preventDefault and pass the event within your HTML.

<a href=/foo onclick= yes_js_login(event)>Lorem ipsum</a>

yes_js_login = function(e) {
  e.preventDefault();
}

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

A solve this adding in the option defaultURL the path my application

<forms loginUrl="/Users/Login" protection="All" timeout="2880" name="001WVCookie" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="/Home/Index" cookieless="UseCookies" enableCrossAppRedirects="false" />

Checkout multiple git repos into same Jenkins workspace

Checking out more than one repo at a time in a single workspace is possible with Jenkins + Git Plugin (maybe only in more recent versions?).

In section "Source-Code-Management", do not select "Git", but "Multiple SCMs" and add several git repositories.

Be sure that in all but one you add as an "Additional behavior" the action "Check out to a sub-directory" and specify an individual subdirectory.

How to get the current working directory in Java?

I hope you want to access the current directory including the package i.e. If your Java program is in c:\myApp\com\foo\src\service\MyTest.java and you want to print until c:\myApp\com\foo\src\service then you can try the following code:

String myCurrentDir = System.getProperty("user.dir")
            + File.separator
            + System.getProperty("sun.java.command")
                    .substring(0, System.getProperty("sun.java.command").lastIndexOf("."))
                    .replace(".", File.separator);
    System.out.println(myCurrentDir);

Note: This code is only tested in Windows with Oracle JRE.

Postgres integer arrays as parameters?

Full Coding Structure

postgresql function

CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
    item_head_list int[])
    RETURNS TABLE(item_display_id integer) 
    LANGUAGE 'sql'

    COST 100
    VOLATILE 
    ROWS 1000
    
AS $BODY$ 
        SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);
    $BODY$;

Model

public class CampaignCreator
    {
        public int item_display_id { get; set; }
        public List<int> pitem_head_id { get; set; }
    }

.NET CORE function

DynamicParameters _parameter = new DynamicParameters();
                _parameter.Add("@item_head_list",obj.pitem_head_id);
                
                string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
                response.data = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);

How to access model hasMany Relation with where condition?

I think this is what you're looking for (Laravel 4, see http://laravel.com/docs/eloquent#querying-relations)

$games = Game::whereHas('video', function($q)
{
    $q->where('available','=', 1);

})->get();

Why check both isset() and !empty()

  • From the PHP Web site, referring to the empty() function:

Returns FALSE if var has a non-empty and non-zero value.

That’s a good thing to know. In other words, everything from NULL, to 0 to “” will return TRUE when using the empty() function.

  • Here is the description of what the isset() function returns:

Returns TRUE if var exists; FALSE otherwise.

In other words, only variables that don’t exist (or, variables with strictly NULL values) will return FALSE on the isset() function. All variables that have any type of value, whether it is 0, a blank text string, etc. will return TRUE.

Deadly CORS when http://localhost is the origin

Chrome will make requests with CORS from a localhost origin just fine. This isn't a problem with Chrome.

The reason you can't load http://stackoverflow.com is that the Access-Control-Allow-Origin headers weren't allowing your localhost origin.

Trim to remove white space

No need for jQuery

JavaScript does have a native .trim() method.

var name = "    John Smith  ";
name = name.trim();

console.log(name); // "John Smith"

Example Here

String.prototype.trim()

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

moment.js get current time in milliseconds?

You could subtract the current time stamp from 12 AM of the same day.

Using current timestamp:

moment().valueOf() - moment().startOf('day').valueOf()

Using arbitrary day:

moment(someDate).valueOf() - moment(someDate).startOf('day').valueOf()

/etc/apt/sources.list" E212: Can't open file for writing

Pre-append your commands with sudo.

For example, Instead of vim textfile.txt, used sudo vim textfile.txt. This will resolve the issue.

Formula to check if string is empty in Crystal Reports

if {le_gur_bond.gur1}="" or IsNull({le_gur_bond.gur1})   Then
    ""
else 
 "and " + {le_gur_bond.gur2} + " of "+ {le_gur_bond.grr_2_address2}

Select distinct rows from datatable in Linq

We can get the distinct similar to the example shown below

 //example
           var  distinctValues =  DetailedBreakDown_Table.AsEnumerable().Select(r => new
            {
                InvestmentVehicleID = r.Field<string>("InvestmentVehicleID"),
                Universe = r.Field<string>("Universe"),
                AsOfDate = _imqDate,
                Ticker = "",
                Cusip = "",
                PortfolioDate = r.Field<DateTime>("PortfolioDate")

            } ).Distinct();

Getting values from JSON using Python

What error is it giving you?

If you do exactly this:

data = json.loads('{"lat":444, "lon":555}')

Then:

data['lat']

SHOULD NOT give you any error at all.

Angular2 Routing with Hashtag to page anchor

Solutions above didn't work for me... This one did it:

First, prepare MyAppComponent for automatic scrolling in ngAfterViewChecked()...

import { Component, OnInit, AfterViewChecked } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component( {
   [...]
} )
export class MyAppComponent implements OnInit, AfterViewChecked {

  private scrollExecuted: boolean = false;

  constructor( private activatedRoute: ActivatedRoute ) {}

  ngAfterViewChecked() {

    if ( !this.scrollExecuted ) {
      let routeFragmentSubscription: Subscription;

      // Automatic scroll
      routeFragmentSubscription =
        this.activatedRoute.fragment
          .subscribe( fragment => {
            if ( fragment ) {
              let element = document.getElementById( fragment );
              if ( element ) {
                element.scrollIntoView();

                this.scrollExecuted = true;

                // Free resources
                setTimeout(
                  () => {
                    console.log( 'routeFragmentSubscription unsubscribe' );
                    routeFragmentSubscription.unsubscribe();
                }, 1000 );

              }
            }
          } );
    }

  }

}

Then, navigate to my-app-route sending prodID hashtag

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component( {
   [...]
} )
export class MyOtherComponent {

  constructor( private router: Router ) {}

  gotoHashtag( prodID: string ) {
    this.router.navigate( [ '/my-app-route' ], { fragment: prodID } );
  }

}

Angular 2: How to call a function after get a response from subscribe http.post

You can add a callback function to your list of get_category(...) parameters.

Ex:

 get_categories(number, callback){
 this.http.post( url, body, {headers: headers, withCredentials:true})
    .subscribe( 
      response => {
        this.total = response.json();
        callback(); 

      }, error => {
    }
  ); 

}

And then you can just call get_category(...) like this:

this.get_category(1, name_of_function);

convert a char* to std::string

std::string has a constructor for this:

const char *s = "Hello, World!";
std::string str(s);

Note that this construct deep copies the character list at s and s should not be nullptr, or else behavior is undefined.

How to add a response header on nginx when using proxy_pass?

There is a module called HttpHeadersMoreModule that gives you more control over headers. It does not come with Nginx and requires additional installation. With it, you can do something like this:

location ... {
  more_set_headers "Server: my_server";
}

That will "set the Server output header to the custom value for any status code and any content type". It will replace headers that are already set or add them if unset.

How to use private Github repo as npm dependency

It can be done via https and oauth or ssh.

https and oauth: create an access token that has "repo" scope and then use this syntax:

"package-name": "git+https://<github_token>:[email protected]/<user>/<repo>.git"

or

ssh: setup ssh and then use this syntax:

"package-name": "git+ssh://[email protected]:<user>/<repo>.git"

(note the use of colon instead of slash before user)

Using python map and other functional tools

Would this do it?

foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]

def maptest2(bar):
  print bar

def maptest(foo):
  print foo
  map(maptest2, bars)

map(maptest, foos)

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

Same issue for me... Upload app archives from Xcode (7.3.1). Connect to iTunesCo with both Chrome and Safari...

  • 20 august: v0.1.3 | b0.0.1 -> upload done -> never appeared on iTunesCo
  • 23 august: v0.1.4 | b0.0.1 -> upload done -> processing on iTunesCo
  • 23 august: v0.1.4 | b0.0.2 -> upload done -> processing on iTunesCo
  • 23 august: v0.1.4 | b0.0.3 -> upload done -> never appeared on iTunesCo
  • 24 august: v0.1.5 | b0.0.1 -> upload done -> available 5min later

The way it works has no logic... So I agree with @teapen:

...don't wait for Apple, just increase build and upload again...

How to print a specific row of a pandas DataFrame?

To print a specific row we have couple of pandas method

  1. loc - It only get label i.e column name or Features
  2. iloc - Here i stands for integer, actually row number
  3. ix - It is a mix of label as well as integer

How to use for specific row

  1. loc
df.loc[row,column]

For first row and all column

df.loc[0,:]

For first row and some specific column

df.loc[0,'column_name']
  1. iloc

For first row and all column

df.iloc[0,:]

For first row and some specific column i.e first three cols

df.iloc[0,0:3]

How do I set a checkbox in razor view?

The syntax in your last line is correct.

 @Html.CheckBoxFor(x => x.Test, new { @checked = "checked" })

That should definitely work. It is the correct syntax. If you have an existing model and AllowRating is set to true then MVC will add the checked attribute automatically. If AllowRating is set to false MVC won't add the attribute however if desired you can using the above syntax.

Filtering Table rows using Jquery

There's no need to build an array. You can address the DOM directly.

Try :

rows.hide();
$.each(data, function(i, v){
    rows.filter(":contains('" + v + "')").show();
});

DEMO

EDIT

To discover the qualifying rows without displaying them immediately, then pass them to a function :

$("#searchInput").keyup(function() {
    var rows = $("#fbody").find("tr").hide();
    var data = this.value.split(" ");
    var _rows = $();//an empty jQuery collection
    $.each(data, function(i, v) {
        _rows.add(rows.filter(":contains('" + v + "')");
    });
    myFunction(_rows);
});

UPDATED DEMO

Mockito How to mock and assert a thrown exception?

Make the exception happen like this:

when(obj.someMethod()).thenThrow(new AnException());

Verify it has happened either by asserting that your test will throw such an exception:

@Test(expected = AnException.class)

Or by normal mock verification:

verify(obj).someMethod();

The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).

What's the difference between commit() and apply() in SharedPreferences

tl;dr:

  • commit() writes the data synchronously (blocking the thread its called from). It then informs you about the success of the operation.
  • apply() schedules the data to be written asynchronously. It does not inform you about the success of the operation.
  • If you save with apply() and immediately read via any getX-method, the new value will be returned!
  • If you called apply() at some point and it's still executing, any calls to commit() will block until all past apply-calls and the current commit-call are finished.

More in-depth information from the SharedPreferences.Editor Documentation:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

The SharedPreferences.Editor interface isn't expected to be implemented directly. However, if you previously did implement it and are now getting errors about missing apply(), you can simply call commit() from apply().

How to drop a table if it exists?

From SQL Server 2016 you can use

DROP TABLE IF EXISTS dbo.Scores

Reference: DROP IF EXISTS - new thing in SQL Server 2016

It will be in SQL Azure Database soon.

Which is faster: Stack allocation or Heap allocation

In general, stack allocation is faster than heap allocation as mentioned by almost every answer above. A stack push or pop is O(1), whereas allocating or freeing from a heap could require a walk of previous allocations. However you shouldn't usually be allocating in tight, performance-intensive loops, so the choice will usually come down to other factors.

It might be good to make this distinction: you can use a "stack allocator" on the heap. Strictly speaking, I take stack allocation to mean the actual method of allocation rather than the location of the allocation. If you're allocating a lot of stuff on the actual program stack, that could be bad for a variety of reasons. On the other hand, using a stack method to allocate on the heap when possible is the best choice you can make for an allocation method.

Since you mentioned Metrowerks and PPC, I'm guessing you mean Wii. In this case memory is at a premium, and using a stack allocation method wherever possible guarantees that you don't waste memory on fragments. Of course, doing this requires a lot more care than "normal" heap allocation methods. It's wise to evaluate the tradeoffs for each situation.

How to toggle font awesome icon on click?

Simply call jQuery's toggleClass() on the i element contained within your a element(s) to toggle either the plus and minus icons:

...click(function() {
    $(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});

Note that this assumes that a class of fa-plus-circle is added to your i element by default.

JSFiddle demo.

Cannot attach the file *.mdf as database

Ran into the similar problem not exactly the same, A case of Database already existed the issue was solved by following code.

_x000D_
_x000D_
<add name="DefaultConnection" connectionString="Data Source=.;AttachDbFilename=|DataDirectory|\aspnet-EjournalParsing-20180925054839.mdf;Initial Catalog=aspnet-EjournalParsing-20180925054839;Integrated Security=True"_x000D_
      providerName="System.Data.SqlClient" />
_x000D_
_x000D_
_x000D_

Build Maven Project Without Running Unit Tests

Run following command:

mvn clean install -DskipTests=true

running multiple bash commands with subprocess

I just stumbled on a situation where I needed to run a bunch of lines of bash code (not separated with semicolons) from within python. In this scenario the proposed solutions do not help. One approach would be to save a file and then run it with Popen, but it wasn't possible in my situation.

What I ended up doing is something like:

commands = '''
echo "a"
echo "b"
echo "c"
echo "d"
'''

process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands)
print out

So I first create the child bash process and after I tell it what to execute. This approach removes the limitations of passing the command directly to the Popen constructor.

Declare variable in SQLite and use it

For a read-only variable (that is, a constant value set once and used anywhere in the query), use a Common Table Expression (CTE).

WITH const AS (SELECT 'name' AS name, 10 AS more)
SELECT table.cost, (table.cost + const.more) AS newCost
FROM table, const 
WHERE table.name = const.name

SQLite WITH clause

How do I get the difference between two Dates in JavaScript?

Thanks @Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin. Here's the simplified end solution:

    // don't update end date if there's already an end date but not an old start date
    if (!oldEnd || oldBegin) {
        var selectedDateSpan = 1800000; // 30 minutes
        if (oldEnd) {
            selectedDateSpan = oldEnd - oldBegin;
        }

       newEnd = new Date(newBegin.getTime() + selectedDateSpan));
    }

How do you find the row count for all your tables in Postgres

Simple Two Steps:
(Note : No need to change anything - just copy paste)
1. create function

create function 
cnt_rows(schema text, tablename text) returns integer
as
$body$
declare
  result integer;
  query varchar;
begin
  query := 'SELECT count(1) FROM ' || schema || '.' || tablename;
  execute query into result;
  return result;
end;
$body$
language plpgsql;

2. Run this query to get rows count for all the tables

select sum(cnt_rows) as total_no_of_rows from (select 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE') as subq;

or

To get rows counts tablewise

select
  table_schema,
  table_name, 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE'
order by 3 desc;

Regular expression to remove HTML tags from a string

You could do it with jsoup http://jsoup.org/

Whitelist whitelist = Whitelist.none();
String cleanStr = Jsoup.clean(yourText, whitelist);

Django TemplateDoesNotExist?

I added this

TEMPLATE_DIRS = (
    os.path.join(SETTINGS_PATH, 'templates'),
)

and it still showed the error, then I realized that in another project the templates was showing without adding that code in settings.py file so I checked that project and I realized that I didn't create a virtual environment in this project so I did

virtualenv env 

and it worked, don't know why

Capture screenshot of active window?

You can use the code from this question: How can I save a screenshot directly to a file in Windows?

Just change WIN32_API.GetDesktopWindow() to the Handle property of the window you want to capture.

Converting Hexadecimal String to Decimal Integer

//package com.javatutorialhq.tutorial;

import java.util.Scanner;

/* * Java code convert hexadecimal to decimal */ 
public class HexToDecimal {

    public static void main(String[] args) {

        // TODO Auto-generated method stub 

        System.out.print("Hexadecimal Input:");

        // read the hexadecimal input from the console 

        Scanner s = new Scanner(System.in); 

        String inputHex = s.nextLine();

        try{ 

// actual conversion of hex to decimal

            Integer outputDecimal = Integer.parseInt(inputHex, 16);

            System.out.println("Decimal Equivalent : "+outputDecimal);


        }

        catch(NumberFormatException ne){

            // Printing a warning message if the input is not a valid hex number

            System.out.println("Invalid Input"); 

        }

        finally{ s.close();

        }
    } 
}

How can I hide or encrypt JavaScript code?

The only safe way to protect your code is not giving it away. With client deployment, there is no avoiding the client having access to the code.

So the short answer is: You can't do it

The longer answer is considering flash or Silverlight. Although I believe silverlight will gladly give away it's secrets with reflector running on the client.

I'm not sure if something simular exists with the flash platform.

QLabel: set color of text and background

I add this answer because I think it could be useful to anybody.

I step into the problem of setting RGBA colors (that is, RGB color with an Alpha value for transparency) for color display labels in my painting application.

As I came across the first answer, I was unable to set an RGBA color. I have also tried things like:

myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())

where color is an RGBA color.

So, my dirty solution was to extend QLabel and override paintEvent() method filling its bounding rect.

Today, I've open up the qt-assistant and read the style reference properties list. Affortunately, it has an example that states the following:

QLineEdit { background-color: rgb(255, 0, 0) }

Thats open up my mind in doing something like the code below, as an example:

myLabel= QLabel()
myLabel.setAutoFillBackground(True) # This is important!!
color  = QtGui.QColor(233, 10, 150)
alpha  = 140
values = "{r}, {g}, {b}, {a}".format(r = color.red(),
                                     g = color.green(),
                                     b = color.blue(),
                                     a = alpha
                                     )
myLabel.setStyleSheet("QLabel { background-color: rgba("+values+"); }")

Note that setAutoFillBackground() set in False will not make it work.

Regards,

Upload Progress Bar in PHP

Implementation of the upload progress bar is easy and doesn't require any additional PHP extension, JavaScript or Flash. But you need PHP 5.4 and newer.

You have to enable collecting of the upload progress information by setting the directive session.upload_progress.enabled to On in php.ini.

Then add a hidden input to the HTML upload form just before any other file inputs. HTML attribute name of that hidden input should be the same as the value of the directive session.upload_progress.name from php.ini (eventually preceded by session.upload_progress.prefix). The value attribute is up to you, it will be used as part of the session key.

HTML form could looks like this:

<form action="upload.php" method="POST" enctype="multipart/form-data">
   <input type="hidden" name="<?php echo ini_get('session.upload_progress.prefix').ini_get('session.upload_progress.name'); ?>" value="myupload" />
   <input type="file" name="file1" />
   <input type="submit" />
</form>

When you send this form, PHP should create a new key in the $_SESSION superglobal structure which will be populated with the upload status information. The key is concatenated name and value of the hidden input.

In PHP you can take a look at populated upload information:

var_dump($_SESSION[
    ini_get('session.upload_progress.prefix')
   .ini_get('session.upload_progress.name')
   .'_myupload'
]);

The output will look similarly to the following:

$_SESSION["upload_progress_myupload"] = array(
  "start_time" => 1234567890,   // The request time
  "content_length" => 57343257, // POST content length
  "bytes_processed" => 54321,   // Amount of bytes received and processed
  "done" => false,              // true when the POST handler has finished, successfully or not
  "files" => array(
    0 => array(
      "field_name" => "file1",    // Name of the <input /> field
      // The following 3 elements equals those in $_FILES
      "name" => "filename.ext",
      "tmp_name" => "/tmp/phpxxxxxx",
      "error" => 0,
      "done" => false,            // True when the POST handler has finished handling this file
      "start_time" => 1234567890, // When this file has started to be processed
      "bytes_processed" => 54321, // Number of bytes received and processed for this file
    )
  )
);

There is all the information needed to create a progress bar — you have the information if the upload is still in progress, the information how many bytes is going to be transferred in total and how many bytes has been transferred already.

To present the upload progress to the user, write an another PHP script than the uploading one, which will only look at the upload information in the session and return it in the JSON format, for example. This script can be called periodically, for example every second, using AJAX and information presented to the user.

You are even able to cancel the upload by setting the $_SESSION[$key]['cancel_upload'] to true.

For detailed information, additional settings and user's comments see PHP manual.

Rebasing a Git merge commit

There are two options here.

One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase.

Another is to use the --rebase-merges option on git rebase, which is described as follows from the manual:

By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually."

In Python, how to check if a string only contains certain characters?

Use python Sets when you need to compare hm... sets of data. Strings can be represented as sets of characters quite fast. Here I test if string is allowed phone number. First string is allowed, second not. Works fast and simple.

In [17]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(898) 64-901-63 ');p.issubset(allowed)").timeit()

Out[17]: 0.8106249139964348

In [18]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(950) 64-901-63 ???');p.issubset(allowed)").timeit()

Out[18]: 0.9240323599951807

Never use regexps if you can avoid them.

simulate background-size:cover on <video> or <img>

Based on Daniel de Wit's answer and comments, I searched a bit more. Thanks to him for the solution.

The solution is to use object-fit: cover; which has a great support (every modern browser support it). If you really want to support IE, you can use a polyfill like object-fit-images or object-fit.

Demos :

_x000D_
_x000D_
img {_x000D_
  float: left;_x000D_
  width: 100px;_x000D_
  height: 80px;_x000D_
  border: 1px solid black;_x000D_
  margin-right: 1em;_x000D_
}_x000D_
.fill {_x000D_
  object-fit: fill;_x000D_
}_x000D_
.contain {_x000D_
  object-fit: contain;_x000D_
}_x000D_
.cover {_x000D_
  object-fit: cover;_x000D_
}_x000D_
.none {_x000D_
  object-fit: none;_x000D_
}_x000D_
.scale-down {_x000D_
  object-fit: scale-down;_x000D_
}
_x000D_
<img class="fill" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="contain" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="cover" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="none" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="scale-down" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
_x000D_
_x000D_
_x000D_

and with a parent:

_x000D_
_x000D_
div {_x000D_
  float: left;_x000D_
  width: 100px;_x000D_
  height: 80px;_x000D_
  border: 1px solid black;_x000D_
  margin-right: 1em;_x000D_
}_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
.fill {_x000D_
  object-fit: fill;_x000D_
}_x000D_
.contain {_x000D_
  object-fit: contain;_x000D_
}_x000D_
.cover {_x000D_
  object-fit: cover;_x000D_
}_x000D_
.none {_x000D_
  object-fit: none;_x000D_
}_x000D_
.scale-down {_x000D_
  object-fit: scale-down;_x000D_
}
_x000D_
<div>_x000D_
<img class="fill" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="contain" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="cover" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="none" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="scale-down" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

is there a post render callback for Angular JS directive?

None of the solutions worked for me accept from using a timeout. This is because I was using a template that was dynamically being created during the postLink.

Note however, there can be a timeout of '0' as the timeout adds the function being called to the browser's queue which will occur after the angular rendering engine as this is already in the queue.

Refer to this: http://blog.brunoscopelliti.com/run-a-directive-after-the-dom-has-finished-rendering

How do I combine 2 select statements into one?

select Status, * from WorkItems t1
where  exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
AND TimeStamp>'2009-02-12 18:00:00'

UNION

select 'DELETED', * from WorkItems t1
where  exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
AND TimeStamp>'2009-02-12 18:00:00'
AND NOT (BoolField05=1)

Perhaps that'd do the trick. I can't test it from here though, and I'm not sure what version of SQL you're working against.

Can anyone explain me StandardScaler?

This is useful when you want to compare data that correspond to different units. In that case, you want to remove the units. To do that in a consistent way of all the data, you transform the data in a way that the variance is unitary and that the mean of the series is 0.

Why is sed not recognizing \t as a tab?

TAB=$(printf '\t')
sed "s/${TAB}//g" input_file

It works for me on Red Hat, which will remove tabs from the input file.

How do I reset a sequence in Oracle?

This stored procedure restarts my sequence:

Create or Replace Procedure Reset_Sequence  
  is
  SeqNbr Number;
begin
   /*  Reset Sequence 'seqXRef_RowID' to 0    */
   Execute Immediate 'Select seqXRef.nextval from dual ' Into SeqNbr;
   Execute Immediate 'Alter sequence  seqXRef increment by - ' || TO_CHAR(SeqNbr) ;
   Execute Immediate 'Select seqXRef.nextval from dual ' Into SeqNbr;
   Execute Immediate 'Alter sequence  seqXRef increment by 1';
END;

/

URL Encoding using C#

Better way is to use

Uri.EscapeUriString

to not reference Full Profile of .net 4.

How do I compile jrxml to get jasper?

In eclipse,

  • Install Jaspersoft Studio for eclipse.
  • Right click the .jrxml file and select Open with JasperReports Book Editor
  • Open the Design tab for the .jrxml file.
  • On top of the window you can see the Compile Report icon.

Create a date time with month and day only, no year

There is no such thing like a DateTime without a year!

From what I gather your design is a bit strange:

I would recommend storing a "start" (DateTime including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.

After the event occurs you calculate the next and store that etc.

How can I get the line number which threw exception?

If you don't have the .PBO file:

C#

public int GetLineNumber(Exception ex)
{
    var lineNumber = 0;
    const string lineSearch = ":line ";
    var index = ex.StackTrace.LastIndexOf(lineSearch);
    if (index != -1)
    {
        var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
        if (int.TryParse(lineNumberText, out lineNumber))
        {
        }
    }
    return lineNumber;
}

Vb.net

Public Function GetLineNumber(ByVal ex As Exception)
    Dim lineNumber As Int32 = 0
    Const lineSearch As String = ":line "
    Dim index = ex.StackTrace.LastIndexOf(lineSearch)
    If index <> -1 Then
        Dim lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length)
        If Int32.TryParse(lineNumberText, lineNumber) Then
        End If
    End If
    Return lineNumber
End Function

Or as an extentions on the Exception class

public static class MyExtensions
{
    public static int LineNumber(this Exception ex)
    {
        var lineNumber = 0;
        const string lineSearch = ":line ";
        var index = ex.StackTrace.LastIndexOf(lineSearch);
        if (index != -1)
        {
            var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
            if (int.TryParse(lineNumberText, out lineNumber))
            {
            }
        }
        return lineNumber;
    }
}   

Python find min max and average of a list (array)

from __future__ import division

somelist =  [1,12,2,53,23,6,17] 
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
    min_value = None
    for value in somelist:
        if not min_value:
            min_value = value
        elif value < min_value:
            min_value = value
    return min_value

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

somelist =  [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

SQL Server convert select a column and convert it to a string

SELECT  CAST(<COLUMN Name> AS VARCHAR(3)) + ','
FROM    <TABLE Name>
FOR     XML PATH('')

Decreasing height of bootstrap 3.0 navbar

After spending few hours, adding the following css class fixed my issue.

Work with Bootstrap 3.0.*

.tnav .navbar .container { height: 28px; }

Work with Bootstrap 3.3.4

.navbar-nav > li > a, .navbar-brand {
    padding-top:4px !important; 
    padding-bottom:0 !important;
    height: 28px;
}
.navbar {min-height:28px !important;}

Update Complete code to customize and decrease height of navbar with screenshot.

enter image description here

CSS:

/* navbar */
.navbar-primary .navbar { background:#9f58b5; border-bottom:none; }
.navbar-primary .navbar .nav > li > a {color: #501762;}
.navbar-primary .navbar .nav > li > a:hover {color: #fff; background-color: #8e49a3;}
.navbar-primary .navbar .nav .active > a,.navbar .nav .active > a:hover {color: #fff; background-color: #501762;}
.navbar-primary .navbar .nav li > a .caret, .tnav .navbar .nav li > a:hover .caret {border-top-color: #fff;border-bottom-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover {}
.navbar-primary .navbar .nav > li.dropdown.open > a {color: #fff;background-color: #9f58b5;border-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover .caret, .tnav .navbar .nav > li.dropdown.open > a .caret {border-top-color: #fff;}
.navbar-primary .navbar .navbar-brand {color:#fff;}
.navbar-primary .navbar .nav.pull-right {margin-left: 10px; margin-right: 0;}
.navbar-xs .navbar-primary .navbar { min-height:28px; height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 28px; }
.navbar-sm .navbar-primary .navbar { min-height:40px; height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 40px; }

Usage Code:

<div class="navbar-xs">
   <div class="navbar-primary">
       <nav class="navbar navbar-static-top" role="navigation">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-8">
                 <span class="sr-only">Toggle navigation</span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Brand</a>
          </div>
          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-8">
              <ul class="nav navbar-nav">
                  <li class="active"><a href="#">Home</a></li>
                  <li><a href="#">Link</a></li>
                   <li><a href="#">Link</a></li>
              </ul>
          </div><!-- /.navbar-collapse -->
      </nav>
  </div>
</div>

Set up DNS based URL forwarding in Amazon Route53

If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com and one for redirect-to.final-destination.com. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to read xls with explicit implementation poi classes for xlsx.

G:\Selenium Jar Files\TestData\Data.xls

Either use HSSFWorkbook and HSSFSheet classes or make your implementation more generic by using shared interfaces, like;

Change:

XSSFWorkbook workbook = new XSSFWorkbook(file);

To:

 org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);

And Change:

XSSFSheet sheet = workbook.getSheetAt(0);

To:

org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

Specify an SSH key for git push for a given domain

you most specified in the file config key ssh:

# Default GitHub user
Host one
 HostName gitlab.com
 User git
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/key-one
 IdentitiesOnly yes

#two user
Host two
 HostName gitlab.com
 User git
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/key-two
 IdentitiesOnly yes

Forward X11 failed: Network error: Connection refused

I had the same problem, but it's solved now. Finally, Putty does work with Cigwin-X, and Xming is not an obligatory app for MS-Windows X-server.

Nowadays it's xlaunch, who controls the run of X-window. Certainly, xlaunch.exe must be installed in Cigwin. When run in interactive mode it asks for "extra settings". You should add "-listen tcp" to additional param field, since Cigwin-X does not listen TCP by default.

In order to not repeat these steps, you may save settings to the file. And run xlaunch.exe via its shortcut with modified CLI inside. Something like

C:\cygwin64\bin\xlaunch.exe -run C:\cygwin64\config.xlaunch

MySQL table is marked as crashed and last (automatic?) repair failed

Go to data_dir and remove the Your_table.TMP file after repairing <Your_table> table.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

I've used these for a long time - no idea where they came from at this point... Note that the inputs and outputs, except for the angle in degrees, are in the range of 0 to 1.0.

NOTE: this code does no real sanity checking on inputs. Proceed with caution!

typedef struct {
    double r;       // a fraction between 0 and 1
    double g;       // a fraction between 0 and 1
    double b;       // a fraction between 0 and 1
} rgb;

typedef struct {
    double h;       // angle in degrees
    double s;       // a fraction between 0 and 1
    double v;       // a fraction between 0 and 1
} hsv;

static hsv   rgb2hsv(rgb in);
static rgb   hsv2rgb(hsv in);

hsv rgb2hsv(rgb in)
{
    hsv         out;
    double      min, max, delta;

    min = in.r < in.g ? in.r : in.g;
    min = min  < in.b ? min  : in.b;

    max = in.r > in.g ? in.r : in.g;
    max = max  > in.b ? max  : in.b;

    out.v = max;                                // v
    delta = max - min;
    if (delta < 0.00001)
    {
        out.s = 0;
        out.h = 0; // undefined, maybe nan?
        return out;
    }
    if( max > 0.0 ) { // NOTE: if Max is == 0, this divide would cause a crash
        out.s = (delta / max);                  // s
    } else {
        // if max is 0, then r = g = b = 0              
        // s = 0, h is undefined
        out.s = 0.0;
        out.h = NAN;                            // its now undefined
        return out;
    }
    if( in.r >= max )                           // > is bogus, just keeps compilor happy
        out.h = ( in.g - in.b ) / delta;        // between yellow & magenta
    else
    if( in.g >= max )
        out.h = 2.0 + ( in.b - in.r ) / delta;  // between cyan & yellow
    else
        out.h = 4.0 + ( in.r - in.g ) / delta;  // between magenta & cyan

    out.h *= 60.0;                              // degrees

    if( out.h < 0.0 )
        out.h += 360.0;

    return out;
}


rgb hsv2rgb(hsv in)
{
    double      hh, p, q, t, ff;
    long        i;
    rgb         out;

    if(in.s <= 0.0) {       // < is bogus, just shuts up warnings
        out.r = in.v;
        out.g = in.v;
        out.b = in.v;
        return out;
    }
    hh = in.h;
    if(hh >= 360.0) hh = 0.0;
    hh /= 60.0;
    i = (long)hh;
    ff = hh - i;
    p = in.v * (1.0 - in.s);
    q = in.v * (1.0 - (in.s * ff));
    t = in.v * (1.0 - (in.s * (1.0 - ff)));

    switch(i) {
    case 0:
        out.r = in.v;
        out.g = t;
        out.b = p;
        break;
    case 1:
        out.r = q;
        out.g = in.v;
        out.b = p;
        break;
    case 2:
        out.r = p;
        out.g = in.v;
        out.b = t;
        break;

    case 3:
        out.r = p;
        out.g = q;
        out.b = in.v;
        break;
    case 4:
        out.r = t;
        out.g = p;
        out.b = in.v;
        break;
    case 5:
    default:
        out.r = in.v;
        out.g = p;
        out.b = q;
        break;
    }
    return out;     
}

How do I use installed packages in PyCharm?

I'm new to PyCharm (using 2018.3.4 CE) and Python so I rotely tried to follow each of the above suggestions to access the PIL (Pillow) package which I knew was in system-site-packages. None worked. I was about to give up for the night when I happened to notice the venv/pyvenv.cfg file under my project in the Project Explorer window. I found the line "include-system-site-packages = false" in that file and so I changed it to "true". Problem solved.

jQuery send string as POST parameters

$.ajax({
    type: 'POST',    
    url:'http://nakolesah.ru/',
    data:'foo='+ bar+'&calibri='+ nolibri,
    success: function(msg){
        alert('wow' + msg);
    }
});

Change WPF window background image in C# code

What about this:

new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "Images/icon.png")))

or alternatively, this:

this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/myapp;component/Images/icon.png")));

How do I define the name of image built with docker-compose

Depending on your use case, you can use an image which has already been created and specify it's name in docker-compose.

We have a production use case where our CI server builds a named Docker image. (docker build -t <specific_image_name> .). Once the named image is specified, our docker-compose always builds off of the specific image. This allows a couple of different possibilities:

1- You can ensure that where ever you run your docker-compose from, you will always be using the latest version of that specific image.

2- You can specify multiple named images in your docker-compose file and let them be auto-wired through the previous build step.

So, if your image is already built, you can name the image with docker-compose. Remove build and specify image:

wildfly:
  image: my_custom_wildfly_image
  container_name: wildfly_server
  ports:
   - 9990:9990
   - 80:8080
  environment:
   - MYSQL_HOST=mysql_server
   - MONGO_HOST=mongo_server
   - ELASTIC_HOST=elasticsearch_server
  volumes:
   - /Volumes/CaseSensitive/development/wildfly/deployments/:/opt/jboss/wildfly/standalone/deployments/
  links:
   - mysql:mysql_server
   - mongo:mongo_server
   - elasticsearch:elasticsearch_server

How do I Convert DateTime.now to UTC in Ruby?

Try this, works in Ruby:

DateTime.now.to_time.utc

gnuplot plotting multiple line graphs

andyras is completely correct. One minor addition, try this (for example)

plot 'ls.dat' using 4:xtic(1)

This will keep your datafile in the correct order, but also preserve your version tic labels on the x-axis.

403 Forbidden vs 401 Unauthorized HTTP responses

  +-----------------------
  | RESOURCE EXISTS ? (if private it is often checked AFTER auth check)
  +-----------------------
    |       |
 NO |       v YES
    v      +-----------------------
   404     | IS LOGGED-IN ? (authenticated, aka has session or JWT cookie)
   or      +-----------------------
   401        |              |
   403     NO |              | YES
   3xx        v              v
              401            +-----------------------
       (404 no reveal)       | CAN ACCESS RESOURCE ? (permission, authorized, ...)
              or             +-----------------------
             redirect          |            |
             to login       NO |            | YES
                               |            |
                               v            v
                               403          OK 200, redirect, ...
                      (or 404: no reveal)
                      (or 404: resource does not exist if private)
                      (or 3xx: redirection)

Checks are usually done in this order:

  • 404 if resource is public and does not exist or 3xx redirection
  • OTHERWISE:
  • 401 if not logged-in or session expired
  • 403 if user does not have permission to access resource (file, json, ...)
  • 404 if resource does not exist or not willing to reveal anything, or 3xx redirection

UNAUTHORIZED: Status code (401) indicating that the request requires authentication, usually this means user needs to be logged-in (session). User/agent unknown by the server. Can repeat with other credentials. NOTE: This is confusing as this should have been named 'unauthenticated' instead of 'unauthorized'. This can also happen after login if session expired. Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)

FORBIDDEN: Status code (403) indicating the server understood the request but refused to fulfill it. User/agent known by the server but has insufficient credentials. Repeating request will not work, unless credentials changed, which is very unlikely in a short time span. Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)

NOT FOUND: Status code (404) indicating that the requested resource is not available. User/agent known but server will not reveal anything about the resource, does as if it does not exist. Repeating will not work. This is a special use of 404 (github does it for example).

As mentioned by @ChrisH there are a few options for redirection 3xx (301, 302, 303, 307 or not redirecting at all and using a 401):

How do I refresh a DIV content?

To reload a section of the page, you could use jquerys load with the current url and specify the fragment you need, which would be the same element that load is called on, in this case #here:

function updateDiv()
{ 
    $( "#here" ).load(window.location.href + " #here" );
}
  • Don't disregard the space within the load element selector: + " #here"

This function can be called within an interval, or attached to a click event

Callback when CSS3 transition finishes

For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.

var cssAnimate = function(cssClass, callback) {
    var self = this;

    // Checks if correct animation has ended
    var setAnimationListener = function() {
        self.one(
            "webkitAnimationEnd oanimationend msAnimationEnd animationend",
            function(e) {
                if(
                    e.originalEvent.animationName == cssClass &&
                    e.target === e.currentTarget
                ) {
                    callback();
                } else {
                    setAnimationListener();
                }
            }
        );
    }

    self.addClass(cssClass);
    setAnimationListener();
}

I used it kinda like this

cssAnimate.call($("#something"), "fadeIn", function() {
    console.log("Animation is complete");
    // Remove animation class name?
});

Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/

And this seems handy: http://api.jqueryui.com/addClass/


Update

After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.

How to render an array of objects in React?

https://facebook.github.io/react/docs/jsx-in-depth.html#javascript-expressions

You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:

<MyComponent>foo</MyComponent>

<MyComponent>{'foo'}</MyComponent>

This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:

function Item(props) {
  return <li>{props.message}</li>;
}

function TodoList() {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
    <ul>
      {todos.map((message) => <Item key={message} message={message} />)}
    </ul>
  );
}

_x000D_
_x000D_
class First extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {_x000D_
      data: [{name: 'bob'}, {name: 'chris'}],_x000D_
    };_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return (_x000D_
      <ul>_x000D_
        {this.state.data.map(d => <li key={d.name}>{d.name}</li>)}_x000D_
      </ul>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <First />,_x000D_
  document.getElementById('root')_x000D_
);_x000D_
  
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

iOS: Compare two dates

According to Apple documentation of NSDate compare:

Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.

- (NSComparisonResult)compare:(NSDate *)anotherDate

Parameters anotherDate

The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.

Return Value

If:

The receiver and anotherDate are exactly equal to each other, NSOrderedSame

The receiver is later in time than anotherDate, NSOrderedDescending

The receiver is earlier in time than anotherDate, NSOrderedAscending

In other words:

if ([date1 compare:date2] == NSOrderedSame) ...

Note that it might be easier in your particular case to read and write this :

if ([date2 isEqualToDate:date2]) ...

See Apple Documentation about this one.

set default schema for a sql query

SETUSER could work, having a user, even an orphaned user in the DB with the default schema needed. But SETUSER is on the legacy not supported for ever list. So a similar alternative would be to setup an application role with the needed default schema, as long as no cross DB access is needed, this should work like a treat.

C# "as" cast vs classic cast

Null comparison is MUCH faster than throwing and catching exception. Exceptions have significant overhead - stack trace must be assembled etc.

Exceptions should represent an unexpected state, which often doesn't represent the situation (which is when as works better).

JavaScript post request like a form submit

The easiest way is using Ajax Post Request:

$.ajax({
    type: "POST",
    url: 'http://www.myrestserver.com/api',
    data: data,
    success: success,
    dataType: dataType
    });

where:

  • data is an object
  • dataType is the data expected by the server (xml, json, script, text, html)
  • url is the address of your RESt server or any function on the server side that accept the HTTP-POST.

Then in the success handler redirect the browser with something like window.location.

Assert that a method was called in a Python unit test

You can mock out aw.Clear, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:

class MyTest(TestCase):
  def testClear():
    old_clear = aw.Clear
    clear_calls = 0
    aw.Clear = lambda: clear_calls += 1
    aps.Request('nv2', aw)
    assert clear_calls == 1
    aw.Clear = old_clear

Using pymox, you'd do it like this:

class MyTest(mox.MoxTestBase):
  def testClear():
    aw = self.m.CreateMock(aps.Request)
    aw.Clear()
    self.mox.ReplayAll()
    aps.Request('nv2', aw)

How to make an HTTP POST web request

MSDN has a sample.

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main()
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}

Java/ JUnit - AssertTrue vs AssertFalse

assertTrue will fail if the second parameter evaluates to false (in other words, it ensures that the value is true). assertFalse does the opposite.

assertTrue("This will succeed.", true);
assertTrue("This will fail!", false);

assertFalse("This will succeed.", false);
assertFalse("This will fail!", true);

As with many other things, the best way to become familiar with these methods is to just experiment :-).

How do I clear inner HTML

const destroy = container => {
  document.getElementById(container).innerHTML = '';
};

Faster previous

const destroyFast = container => {
  const el = document.getElementById(container);
  while (el.firstChild) el.removeChild(el.firstChild);
};

What processes are using which ports on unix?

Try pfiles PID to show all open files for a process.

Create Django model or update if exists

You can also use update_or_create just like get_or_create and here is the pattern I follow for update_or_create assuming a model Person with id (key), name, age, is_manager as attributes -

update_values = {"is_manager": False}
new_values = {"name": "Bob", "age": 25, "is_manager":True}

obj, created = Person.objects.update_or_create(identifier='id',
                                               defaults=update_values)
if created:
    obj.update(**new_values)

How to compare each item in a list with the rest, only once?

This code will count frequency and remove duplicate elements:

from collections import Counter

str1='the cat sat on the hat hat'

int_list=str1.split();

unique_list = []
for el in int_list:

    if el not in unique_list:
        unique_list.append(el)
    else:
        print "Element already in the list"

print unique_list

c=Counter(int_list)

c.values()

c.keys()

print c

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

What are the differences between normal and slim package of jquery?

I could see $.ajax is removed from jQuery slim 3.2.1

From the jQuery docs

You can also use the slim build, which excludes the ajax and effects modules

Below is the comment from the slim version with the features removed

/*! jQuery v3.2.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */

Change directory command in Docker?

RUN git clone http://username:password@url/example.git
WORKDIR /folder
RUN make

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

If you are using Jersey 2.x use following dependency:

<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.XX</version>
</dependency>  

Where XX could be any particular version you look for. Jersey Containers.

MISCONF Redis is configured to save RDB snapshots

# on redis 6.0.4 
# if show error 'MISCONF Redis is configured to save RDB snapshots'
# Because redis doesn't have permissions to create dump.rdb file
sudo redis/bin/redis-server 
sudo redis/bin/redis-cli

How to set focus on an input field after rendering?

Using React Hooks / Functional components with Typescript, you can use the useRef hook with HTMLInputElement as the generic parameter of useRef:

import React, { useEffect, useRef } from 'react';

export default function MyComponent(): JSX.Element {
    const inputReference = useRef<HTMLInputElement>(null);

    useEffect(() => {
        inputReference.current?.focus();
    }, []);

    return (
        <div>
            <input ref={inputReference} />
        </div>
    );
}

Or if using reactstrap, supply inputReference to innerRef instead of ref:

import React, { useEffect, useRef } from 'react';
import { Input } from 'reactstrap';

export default function MyComponent(): JSX.Element {
    const inputReference = useRef<HTMLInputElement>(null);

    useEffect(() => {
        inputReference.current?.focus();
    }, []);

    return (
        <div>
            <Input innerRef={inputReference} />
        </div>
    );
}

Is there a CSS parent selector?

Just an idea for horizontal menu...

Part of HTML

<div class='list'>
  <div class='item'>
    <a>Link</a>
  </div>
  <div class='parent-background'></div>
  <!-- submenu takes this place -->
</div>

Part of CSS

/* Hide parent backgrounds... */
.parent-background {
  display: none; }

/* ... and show it when hover on children */
.item:hover + .parent-background {
  display: block;
  position: absolute;
  z-index: 10;
  top: 0;
  width: 100%; }

Updated demo and the rest of code

Another example how to use it with text-inputs - select parent fieldset

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:

SELECT * FROM match WHERE id NOT IN 
    ( SELECT id FROM email WHERE id IS NOT NULL) ;

SELECT
    m.*
FROM
    match m
    LEFT OUTER JOIN email e ON
        m.id = e.id
        AND e.id IS NOT NULL
WHERE
    e.id IS NULL

The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.

How do I change the text of a span element using JavaScript?

document.getElementById("myspan").textContent="newtext";

this will select dom-node with id myspan and change it text content to new text

Regex to extract substring, returning 2 results for some reason

Just get rid of the parenthesis and that will give you an array with one element and:

  • Change this line

var test = tesst.match(/a(.*)j/);

  • To this

var test = tesst.match(/a.*j/);

If you add parenthesis the match() function will find two match for you one for whole expression and one for the expression inside the parenthesis

  • Also according to developer.mozilla.org docs :

If you only want the first match found, you might want to use RegExp.exec() instead.

You can use the below code:

RegExp(/a.*j/).exec("afskfsd33j")

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

"Submit is not a function" error in JavaScript

I had the same issue when i was creating a MVC application using with master pages. Tried looking for element with 'submit' as names as mentioned above but it wasn't the case.

For my case it created multiple tags on my page so there were some issues referencing the correct form.

To work around this i'll let the button handle which form object to use:

onclick="return SubmitForm(this.form)"

and with the js:

function SubmitForm(frm) {
    frm.submit();
}

How do I get a HttpServletRequest in my spring beans?

this should do it

((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getRequestURI();

Django - "no module named django.core.management"

This problem occurs when django is not installed on your computer. When django is not installed which means django.core.management module is also is not installed. So it didn't find this module and it gives error.
For solving this problem we should install django using pip. Open comand line cmd(on windows) and type as

pip install django

This command will install django in your computer. If you don't have install pip. you should install pip. Here how to install pip on windows

Android - running a method periodically using postDelayed() call

Perhaps involve the activity's life-cycle methods to achieve this:

Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      handler.post(sendData);
}

@Override
protected void onDestroy() {
      super.onDestroy();
      handler.removeCallbacks(sendData);
}


private final Runnable sendData = new Runnable(){
    public void run(){
        try {
            //prepare and send the data here..


            handler.postDelayed(this, 1000);    
        }
        catch (Exception e) {
            e.printStackTrace();
        }   
    }
};

In this approach, if you press back-key on your activity or call finish();, it will also stop the postDelayed callings.

How do I delete a local repository in git?

Delete the .git directory in the root-directory of your repository if you only want to delete the git-related information (branches, versions).

If you want to delete everything (git-data, code, etc), just delete the whole directory.

.git directories are hidden by default, so you'll need to be able to view hidden files to delete it.

Correct set of dependencies for using Jackson mapper

Apart from fixing the imports, do a fresh maven clean compile -U. Note the -U option, that brings in new dependencies which sometimes the editor has hard time with. Let the compilation fail due to un-imported classes, but at least you have an option to import them after the maven command.

Just doing Maven->Reimport from Intellij did not work for me.

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

OpenCV in Android Studio

This worked for me and was as easy as adding a gradle dependancy:

https://bintray.com/seesaa/maven/opencv#

https://github.com/seesaa/opencv-android

The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.

It seems to build and the suggested test:

static {
    OpenCVLoader.initDebug();
}

spits out a bunch of output that looks about right to me.

Java: convert List<String> to a String

EDIT

I also notice the toString() underlying implementation issue, and about the element containing the separator but I thought I was being paranoid.

Since I've got two comments on that regard, I'm changing my answer to:

static String join( List<String> list , String replacement  ) {
    StringBuilder b = new StringBuilder();
    for( String item: list ) { 
        b.append( replacement ).append( item );
    }
    return b.toString().substring( replacement.length() );
}

Which looks pretty similar to the original question.

So if you don't feel like adding the whole jar to your project you may use this.

I think there's nothing wrong with your original code. Actually, the alternative that everyone's is suggesting looks almost the same ( although it does a number of additional validations )

Here it is, along with the Apache 2.0 license.

public static String join(Iterator iterator, String separator) {
    // handle null, zero and one elements before building a buffer
    if (iterator == null) {
        return null;
    }
    if (!iterator.hasNext()) {
        return EMPTY;
    }
    Object first = iterator.next();
    if (!iterator.hasNext()) {
        return ObjectUtils.toString(first);
    }

    // two or more elements
    StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
    if (first != null) {
        buf.append(first);
    }

    while (iterator.hasNext()) {
        if (separator != null) {
            buf.append(separator);
        }
        Object obj = iterator.next();
        if (obj != null) {
            buf.append(obj);
        }
    }
    return buf.toString();
}

Now we know, thank you open source

How can I detect the encoding/codepage of a text file

If you're looking to detect non-UTF encodings (i.e. no BOM), you're basically down to heuristics and statistical analysis of the text. You might want to take a look at the Mozilla paper on universal charset detection (same link, with better formatting via Wayback Machine).

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Use ` backticks for MYSQL reserved words...

table name "table" is reserved word for MYSQL...

so your query should be as follows...

$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";

Uploading Images to Server android

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);

ABOVE CODE TO SELECT IMAGE FROM GALLERY

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1)
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = data.getData();

            String filePath = getPath(selectedImage);
            String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
            image_name_tv.setText(filePath);

            try {
                if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
                    //FINE
                } else {
                    //NOT IN REQUIRED FORMAT
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}

public String getPath(Uri uri) {
    String[] projection = {MediaColumns.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    column_index = cursor
            .getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();
    imagePath = cursor.getString(column_index);

    return cursor.getString(column_index);
}

NOW POST THE DATA USING MULTIPART FORM DATA

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");

Multipart FORM DATA

MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
    File file = new File(filePath);
    Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
    Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
    mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}

FINALLY POST DATA TO SERVER

httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

Saty described the differences between them. For your practice, you can use datetime in order to keep the output of NOW().

For example:

CREATE TABLE Orders
(
  OrderId int NOT NULL,
  ProductName varchar(50) NOT NULL,
  OrderDate datetime NOT NULL DEFAULT NOW(),
  PRIMARY KEY (OrderId)
)

You can read more at w3schools.

Changing Tint / Background color of UITabBar

 [[UITabBar appearance] setTintColor:[UIColor redColor]];
 [[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];

Convert DataTable to CSV stream

I don't know if this converted from VB to C# ok but if you don't want quotes around your numbers, you might compare the data type as follows..

public string DataTableToCSV(DataTable dt)
{
    StringBuilder sb = new StringBuilder();
    if (dt == null)
        return "";

    try {
        // Create the header row
        for (int i = 0; i <= dt.Columns.Count - 1; i++) {
            // Append column name in quotes
            sb.Append("\"" + dt.Columns[i].ColumnName + "\"");
            // Add carriage return and linefeed if last column, else add comma
            sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
        }


        foreach (DataRow row in dt.Rows) {
            for (int i = 0; i <= dt.Columns.Count - 1; i++) {
                // Append value in quotes
                //sb.Append("""" & row.Item(i) & """")

                // OR only quote items that that are equivilant to strings
                sb.Append(object.ReferenceEquals(dt.Columns[i].DataType, typeof(string)) || object.ReferenceEquals(dt.Columns[i].DataType, typeof(char)) ? "\"" + row[i] + "\"" : row[i]);

                // Append CR+LF if last field, else add Comma
                sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
            }
        }
        return sb.ToString;
    } catch (Exception ex) {
        // Handle the exception however you want
        return "";
    }

}

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

CSS-Only Scrollable Table with fixed headers

This answer will be used as a placeholder for the not fully supported position: sticky and will be updated over time. It is currently advised to not use the native implementation of this in a production environment.

See this for the current support: https://caniuse.com/#feat=css-sticky


Use of position: sticky

An alternative answer would be using position: sticky. As described by W3C:

A stickily positioned box is positioned similarly to a relatively positioned box, but the offset is computed with reference to the nearest ancestor with a scrolling box, or the viewport if no ancestor has a scrolling box.

This described exactly the behavior of a relative static header. It would be easy to assign this to the <thead> or the first <tr> HTML-tag, as this should be supported according to W3C. However, both Chrome, IE and Edge have problems assigning a sticky position property to these tags. There also seems to be no priority in solving this at the moment.

What does seem to work for a table element is assigning the sticky property to a table-cell. In this case the <th> cells.

Because a table is not a block-element that respects the static size you assign to it, it is best to use a wrapper element to define the scroll-overflow.

The code

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  height: 150px;_x000D_
  overflow: auto_x000D_
}_x000D_
_x000D_
table th {_x000D_
  position: -webkit-sticky;_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
_x000D_
/* == Just general styling, not relevant :) == */_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th {_x000D_
  background-color: #1976D2;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  padding: 1em .5em;_x000D_
}_x000D_
_x000D_
table tr {_x000D_
  color: #212121;_x000D_
}_x000D_
_x000D_
table tr:nth-child(odd) {_x000D_
  background-color: #BBDEFB;_x000D_
}
_x000D_
<div>_x000D_
  <table border="0">_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>head1</th>_x000D_
        <th>head2</th>_x000D_
        <th>head3</th>_x000D_
        <th>head4</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tr>_x000D_
      <td>row 1, cell 1</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In this example I use a simple <div> wrapper to define the scroll-overflow done with a static height of 150px. This can of course be any size. Now that the scrolling box has been defined, the sticky <th> elements will corespondent "to the nearest ancestor with a scrolling box", which is the div-wrapper.


Use of a position: sticky polyfill

Non-supported devices can make use of a polyfill, which implements the behavior through code. An example is stickybits, which resembles the same behavior as the browser's implemented position: sticky.

Example with polyfill: http://jsfiddle.net/7UZA4/6957/

Set a button background image iPhone programmatically

You can set an background image without any code!

Just press the button you want an image to in Main.storyboard, then, in the utilities bar to the right, press the attributes inspector and set the background to the image you want! Make sure you have the picture you want in the supporting files to the left.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The problem with your macro is that once you have opened your destination Workbook (xlw in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.

Sub UploadData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Dim myWb as Excel.Workbook

    Set myWb = ActiveWorkbook
    Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
    xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
    xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text

    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub

If you prefer, you could also use myWb.Activate to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).

How to check that Request.QueryString has a specific value or not in ASP.NET?

What about a more direct approach?

if (Request.QueryString.AllKeys.Contains("mykey")

Executing <script> injected by innerHTML after AJAX call

Here is a function you can use to parse AJAX responses, especially if you use minifiedjs and want it to execute the returned Javascript or just want to parse the scripts without adding them to the DOM, it handles exception errors as well. I used this code in php4sack library and it is useful outside of the library.

function parseScript(_source) {
    var source = _source;
    var scripts = new Array();

    // Strip out tags
    while(source.toLowerCase().indexOf("<script") > -1 || source.toLowerCase().indexOf("</script") > -1) {
        var s = source.toLowerCase().indexOf("<script");
        var s_e = source.indexOf(">", s);
        var e = source.toLowerCase().indexOf("</script", s);
        var e_e = source.indexOf(">", e);

        // Add to scripts array
        scripts.push(source.substring(s_e+1, e));
        // Strip from source
        source = source.substring(0, s) + source.substring(e_e+1);
    }

    // Loop through every script collected and eval it
    for(var i=0; i<scripts.length; i++) {
        try {
          if (scripts[i] != '')
          {         
            try  {          //IE
                  execScript(scripts[i]);   
      }
      catch(ex)           //Firefox
      {
        window.eval(scripts[i]);
      }   

            }  
        }
        catch(e) {
            // do what you want here when a script fails
         // window.alert('Script failed to run - '+scripts[i]);
          if (e instanceof SyntaxError) console.log (e.message+' - '+scripts[i]);
                    }
    }
// Return the cleaned source
    return source;
 }

How to escape comma and double quote at same time for CSV file?

Excel has to be able to handle the exact same situation.

Put those things into Excel, save them as CSV, and examine the file with a text editor. Then you'll know the rules Excel is applying to these situations.

Make Java produce the same output.

The formats used by Excel are published, by the way...

****Edit 1:**** Here's what Excel does
****Edit 2:**** Note that php's fputcsv does the same exact thing as excel if you use " as the enclosure.

[email protected]
Richard
"This is what I think"

gets transformed into this:

Email,Fname,Quoted  
[email protected],Richard,"""This is what I think"""

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

You can do like

HTML in PHP :

<?php
     echo "<table>";
     echo "<tr>";
     echo "<td>Name</td>";
     echo "<td>".$name."</td>";
     echo "</tr>";
     echo "</table>";
?>

Or You can write like.

PHP in HTML :

<?php /*Do some PHP calculation or something*/ ?>
     <table>
         <tr>
             <td>Name</td>
             <td><?php echo $name;?></td>
         </tr>
     </table>


<?php /*Do some PHP calculation or something*/ ?> Means:
You can open a PHP tag with <?php, now add your PHP code, then close the tag with ?> and then write your html code. When needed to add more PHP, just open another PHP tag with <?php.

Can we cast a generic object to a custom object type in javascript?

No.

But if you're looking to treat your person1 object as if it were a Person, you can call methods on Person's prototype on person1 with call:

Person.prototype.getFullNamePublic = function(){
    return this.lastName + ' ' + this.firstName;
}
Person.prototype.getFullNamePublic.call(person1);

Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName method.

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Visual Studio 2008 does have a designer that allows you to add FK's. Just right-click the table... Table Properties, then go to the "Add Relations" section.

How to use protractor to check if an element is visible?

This answer will be robust enough to work for elements that aren't on the page, therefore failing gracefully (not throwing an exception) if the selector failed to find the element.

const nameSelector = '[data-automation="name-input"]';
const nameInputIsDisplayed = () => {
    return $$(nameSelector).count()
        .then(count => count !== 0)
}
it('should be displayed', () => {
    nameInputIsDisplayed().then(isDisplayed => {
        expect(isDisplayed).toBeTruthy()
    })
})

Access to the path is denied

I got this problem when I try to save the file without set the file name.

Old Code

File.WriteAllBytes(@"E:\Folder", Convert.FromBase64String(Base64String));

Working Code

File.WriteAllBytes(@"E:\Folder\"+ fileName, Convert.FromBase64String(Base64String));

How to place object files in separate subdirectory

The VPATH lines are wrong, they should be

vpath %.c  src
vpath %.h  src

i.e. not capital and without the = . As it is now, it doesn't find the .h file and thinks it is a target to be made.

How to auto generate migrations with Sequelize CLI from Sequelize models?

I created a small working "migration file generator". It creates files which are working perfectly fine using sequelize db:migrate - even with foreign keys!

You can find it here: https://gist.github.com/manuelbieh/ae3b028286db10770c81

I tested it in an application with 12 different models covering:

  • STRING, TEXT, ENUM, INTEGER, BOOLEAN, FLOAT as DataTypes

  • Foreign key constraints (even reciprocal (user belongsTo team, team belongsTo user as owner))

  • Indexes with name, method and unique properties

LINQ select in C# dictionary

If you are searching by the fieldname1 value, try this:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .Where(d => d.ContainsKey("fieldname1"))
   .Select(d => d["fieldname1"]).Cast<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();

If you are looking by the type of the value in the subDictionary (Dictionary<string, object> explicitly), you may do this:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .SelectMany(d=>d.Values)
   .OfType<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();

Both alternatives will return:

title1
title2
title3
title1
title2
title3

Set multiple system properties Java command line

If the required properties need to set in system then there is no option than -D But if you need those properties while bootstrapping an application then loading properties through the properties files is a best option. It will not require to change build for a single property.

Default nginx client_max_body_size

Pooja Mane's answer worked for me, but I had to put the client_max_body_size variable inside of http section.

enter image description here