Programs & Examples On #Jinfo

jinfo prints Java configuration information for a given Java process or core file or a remote debug server. Configuration information includes Java System properties and Java virtual machine command line flags.

DateTime.MinValue and SqlDateTime overflow

Simply put, don't use DateTime.MinVaue as a default value.

There are a couple of different MinValues out there, depending which environment you are in.

I once had a project, where I was implementing a Windows CE project, I was using the Framework's DateTime.MinValue (year 0001), the database MinValue (1753) and a UI control DateTimePicker (i think it was 1970). So there were at least 3 different MinValues that were leading to strange behavior and unexpected results. (And I believe that there was even a fourth (!) version, I just do not recall where it came from.).

Use a nullable database field and change your value into a Nullable<DateTime> instead. Where there is no valid value in your code, there should not be a value in the database as well. :-)

How do I properly set the permgen size?

Completely removed from java 8 +
Partially removed from java 7 (interned Strings for example)
source

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

If you are using foreignkey then you have to use "on_delete=models.CASCADE" as it will eliminate the complexity developed after deleting the original element from the parent table. As simple as that.

categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE)

How to remove carriage returns and new lines in Postgresql?

OP asked specifically about regexes since it would appear there's concern for a number of other characters as well as newlines, but for those just wanting strip out newlines, you don't even need to go to a regex. You can simply do:

select replace(field,E'\n','');

I think this is an SQL-standard behavior, so it should extend back to all but perhaps the very earliest versions of Postgres. The above tested fine for me in 9.4 and 9.2

wp-admin shows blank page, how to fix it?

I faced the same problem and I tried many things such as trying to login through wp-login.php instead of /wp-admin and adding ob_start() in /wp-admin/index.php (if you hit the url /wp-admin it goes for /wp-admin). It showed login page but entering the username and password shows an error like "cookies are blocked due to unexpected output".

I finally got the solution: it happens because the theme or plugins that you installed are not supported.

How to check and fix:

  • Rename the plugin folder name and theme folder name. If opening /wp-admin and entering a valid username and password the dashboard is shown, then it worked.

  • Revert the folder name of plugin and theme, then activate the themes and plugins one by one, cross-checking with /wp-admin. You will find out the unsupported plugin or theme.

Create directory if it does not exist

[System.IO.Directory]::CreateDirectory('full path to directory')

This internally checks for directory existence, and creates one, if there is no directory. Just one line and native .NET method working perfectly.

Check if record exists from controller in Rails

Why your code does not work?

The where method returns an ActiveRecord::Relation object (acts like an array which contains the results of the where), it can be empty but it will never be nil.

Business.where(id: -1) 
 #=> returns an empty ActiveRecord::Relation ( similar to an array )
Business.where(id: -1).nil? # ( similar to == nil? )
 #=> returns false
Business.where(id: -1).empty? # test if the array is empty ( similar to .blank? )
 #=> returns true

How to test if at least one record exists?

Option 1: Using .exists?

if Business.exists?(user_id: current_user.id)
  # same as Business.where(user_id: current_user.id).exists?
  # ...
else
  # ...
end

Option 2: Using .present? (or .blank?, the opposite of .present?)

if Business.where(:user_id => current_user.id).present?
  # less efficiant than using .exists? (see generated SQL for .exists? vs .present?)
else
  # ...
end

Option 3: Variable assignment in the if statement

if business = Business.where(:user_id => current_user.id).first
  business.do_some_stuff
else
  # do something else
end

This option can be considered a code smell by some linters (Rubocop for example).

Option 3b: Variable assignment

business = Business.where(user_id: current_user.id).first
if business
  # ...
else
  # ...
end

You can also use .find_by_user_id(current_user.id) instead of .where(...).first


Best option:

  • If you don't use the Business object(s): Option 1
  • If you need to use the Business object(s): Option 3

Simple function to sort an array of objects

_x000D_
_x000D_
var library = [_x000D_
        {name: 'Steve', course:'WAP', courseID: 'cs452'}, _x000D_
        {name: 'Rakesh', course:'WAA', courseID: 'cs545'},_x000D_
        {name: 'Asad', course:'SWE', courseID: 'cs542'},_x000D_
];_x000D_
_x000D_
const sorted_by_name = library.sort( (a,b) => a.name > b.name );_x000D_
_x000D_
for(let k in sorted_by_name){_x000D_
    console.log(sorted_by_name[k]);_x000D_
}
_x000D_
_x000D_
_x000D_

Add an object to an Array of a custom class

The array declaration should be:

Car[] garage = new Car[100];

You can also just assign directly:

garage[1] = new Car("Blue");

How to remove the hash from window.location (URL) with JavaScript without page refresh?

I think, it would be more safe

if (window.history) {
    window.history.pushState('', document.title, window.location.href.replace(window.location.hash, ''));
} else {
    window.location.hash = '';
}

Spring Boot @autowired does not work, classes in different package

In my case @component was not working because I initialized that class instance by using new <classname>().

If we initialize instance by conventional Java way anywhere in code, then spring won't add that component in IOC container.

What is the proper way to re-attach detached objects in Hibernate?

In the original post, there are two methods, update(obj) and merge(obj) that are mentioned to work, but in opposite circumstances. If this is really true, then why not test to see if the object is already in the session first, and then call update(obj) if it is, otherwise call merge(obj).

The test for existence in the session is session.contains(obj). Therefore, I would think the following pseudo-code would work:

if (session.contains(obj))
{
    session.update(obj);
}
else 
{
    session.merge(obj);
}

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Connect to SQL Server through PDO using SQL Server Driver

Mind you that in my experience and also of other (PHP - Why is new SQLSRV driver slower than the old mssql driver?) that using PDO_SQLSRV is way slower than through PDO_ODBC.

If you want to use the faster PDO_ODBC you can use:

//use any of these or check exact MSSQL ODBC drivername in "ODBC Data Source Administrator"
$mssqldriver = '{SQL Server}'; 
$mssqldriver = '{SQL Server Native Client 11.0}';
$mssqldriver = '{ODBC Driver 11 for SQL Server}';

$hostname='127.0.0.1';
$dbname='test';
$username='user';
$password='pw';
$dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password);

Git diff between current branch and master but not including unmerged master commits

According to Documentation

git diff Shows changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, changes resulting from a merge, changes between two blob objects, or changes between two files on disk.

In git diff - There's a significant difference between two dots .. and 3 dots ... in the way we compare branches or pull requests in our repository. I'll give you an easy example which demonstrates it easily.

Example: Let's assume we're checking out new branch from master and pushing some code in.

  G---H---I feature (Branch)
 /
A---B---C---D master (Branch)
  • Two dots - If we want to show the diffs between all changes happened in the current time on both sides, We would use the git diff origin/master..feature or just git diff origin/master
    ,output: ( H, I against A, B, C, D )

  • Three dots - If we want to show the diffs between the last common ancestor (A), aka the check point we started our new branch ,we use git diff origin/master...feature,output: (H, I against A ).

  • I'd rather use the 3 dots in most circumstances.

SSIS Connection Manager Not Storing SQL Password

Check the text contents of the connection manager file itself, the password field might be configured in the Project.params file, in which case entering the password into the connection manager window will cause it to not save.

How to resolve merge conflicts in Git repository?

There are 3 steps:

  1. Find which files cause conflicts by command

    git status
    
  2. Check the files, in which you would find the conflicts marked like

    <<<<<<<<head
    blablabla
    
  3. Change it to the way you want it, then commit with commands

    git add solved_conflicts_files
    git commit -m 'merge msg'
    

Upgrade python without breaking yum

If you want to try out rpm packages, you can install binary packages based on the newest Fedora rpms, but recompiled for RHEL6/CentOS6/ScientificLinux-6 on:

http://www.jur-linux.org/download/el-updates/6/

best regards,

Florian La Roche

Best Practices for Custom Helpers in Laravel 5

**

  • Status Helper

** create new helper

<?php

namespace App\Helpers;

use Illuminate\Database\Eloquent\Collection;

class StatusHelper
{
 protected static $_status = [
        1=> [
            'value' => 1,
            'displayName' => 'Active',
        ],
        2 => [
            'value' => 2,
            'displayName' => 'Inactive',
        ],
        3 => [
            'value' => 3,
            'displayName' => 'Delete',
        ],

    ];

     public static function getStatusesList()
    {
        $status = (new Collection(self::$_status))->pluck('displayName', 'value')->toArray();


        return $status;
    }
}

Use for the controller and any view file

use App\Helpers\StatusHelper;

class ExampleController extends Controller
{
        public function index()
        {
            $statusList = StatusHelper::getStatusesList();

            return view('example.index', compact('statusList'));
        }
}

Sleeping in a batch file

Just put this in your batch file where you want the wait.

@ping 127.0.0.1 -n 11 -w 1000 > null

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings] "ProxySettingsPerUser"=dword:00000000

label or @html.Label ASP.net MVC 4

Depends on what your are doing.

If you have SPA (Single-Page Application) the you can use:

<input id="txtName" type="text" />

Otherwise using Html helpers is recommended, to get your controls bound with your model.

how to set default method argument values?

You can't declare default values for the parameters like C# (I believe) lets you, but you could simply just create an overload.

public int doSomething(int arg1, int arg2) {
    //some logic here
    return 0;
}

//overload supplies default values of 1 and 2
public int doSomething() {
    return doSomething(1, 2);
}

If you are going to do something like this please do everyone else who works with your code a favor and make sure you mention in Javadoc comments what the default values you are using are!

Get the previous month's first and last day dates in c#

This is a take on Mike W's answer:

internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
    DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
    DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
    if (returnLastDayOfMonth) return lastDayOfLastMonth;
    return firstDayOfThisMonth.AddMonths(-1);
}

You can call it like so:

dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);

Force encode from US-ASCII to UTF-8 (iconv)

The following converts all files in a folder.

Create backup folder of original files.

mkdir backup

Convert all files in US ASCII encoding to UTF-8 (single line command)

for f in $(file -i * .sql | grep us-ascii | cut -d ':' -f 1); do iconv -f us-ascii -t utf-8 $f -o $ f.utf-8 && mv $f backup / && mv "$f.utf-8" $f; done

Convert all files in encoding ISO 8859-1 to UTF-8 (single line command)

for f $(file -i * .sql | grep iso-8859-1 | cut -d ':' -f 1); do iconv -f iso-8859-1 -t utf-8 $f -o $f.utf-8 && mv $f backup / && mv "$f.utf-8" $f; done

How can I remove a key and its value from an associative array?

Use this function to remove specific arrays of keys without modifying the original array:

function array_except($array, $keys) {
  return array_diff_key($array, array_flip((array) $keys));   
} 

First param pass all array, second param set array of keys to remove.

For example:

$array = [
    'color' => 'red', 
    'age' => '130', 
    'fixed' => true
];
$output = array_except($array, ['color', 'fixed']);
// $output now contains ['age' => '130']

How to unpack an .asar file?

It is possible to upack without node installed using the following 7-Zip plugin:
http://www.tc4shell.com/en/7zip/asar/

Thanks @MayaPosch for mentioning that in this comment.

process.waitFor() never returns

There are several possibilities:

  1. You haven't consumed all the output on the process's stdout.
  2. You haven't consumed all the output on the process's stderr.
  3. The process is waiting for input from you and you haven't provided it, or you haven't closed the process's stdin.
  4. The process is spinning in a hard loop.

Command line tool to dump Windows DLL version?

The listdlls tools from Systernals might do the job: http://technet.microsoft.com/en-us/sysinternals/bb896656.aspx

listdlls -v -d mylib.dll

Download file inside WebView

    mwebView.setDownloadListener(new DownloadListener()
   {

  @Override  


   public void onDownloadStart(String url, String userAgent,
        String contentDisposition, String mimeType,
        long contentLength) {

    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse(url));


    request.setMimeType(mimeType);


    String cookies = CookieManager.getInstance().getCookie(url);


    request.addRequestHeader("cookie", cookies);


    request.addRequestHeader("User-Agent", userAgent);


    request.setDescription("Downloading file...");


    request.setTitle(URLUtil.guessFileName(url, contentDisposition,
            mimeType));


    request.allowScanningByMediaScanner();


    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
                    url, contentDisposition, mimeType));
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    dm.enqueue(request);
    Toast.makeText(getApplicationContext(), "Downloading File",
            Toast.LENGTH_LONG).show();
}});

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

An expansion for those who did a bit of fiddling around like I did.

The following work (from W3):

<input type="text" autofocus />
<input type="text" autofocus="" />
<input type="text" autofocus="autofocus" />
<input type="text" autofocus="AuToFoCuS" />

It is important to note that this does not work in CSS though. I.e. you can't use:

.first-input {
    autofocus:"autofocus"
}

At least it didn't work for me...

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

For MySQL 5.7 on Mac OS X El Capitan:

OS X provides example configuration files at /usr/local/mysql/support-files/my-default.cnf

To add variables, first stop the server and just copy above file to, /usr/local/mysql/etc/my.cnf

cmd : sudo cp /usr/local/mysql/support-files/my-default.cnf /usr/local/mysql/etc/my.cnf

NOTE: create 'etc' folder under 'mysql' in case it doesn't exists.

cmd : sudo mkdir /usr/local/mysql/etc

Once the my.cnf is created under etc. it's time to set variable inside that.

cmd: sudo nano my.cnf

set variables below [mysqld]

[mysqld]
innodb_log_file_size = 512M
innodb_strict_mode = 0

now start a server!

How to change fontFamily of TextView in Android

Here you can see all the avaliable fontFamily values and it's corresponding font file's names(This file is using in android 5.0+). In mobile device, you can find it in:

/system/etc/fonts.xml (for 5.0+)

(For android 4.4 and below using this version, but I think that fonts.xml has a more clear format and easy to understand.)

For example,

    <!-- first font is default -->
20    <family name="sans-serif">
21        <font weight="100" style="normal">Roboto-Thin.ttf</font>
22        <font weight="100" style="italic">Roboto-ThinItalic.ttf</font>
23        <font weight="300" style="normal">Roboto-Light.ttf</font>
24        <font weight="300" style="italic">Roboto-LightItalic.ttf</font>
25        <font weight="400" style="normal">Roboto-Regular.ttf</font>
26        <font weight="400" style="italic">Roboto-Italic.ttf</font>
27        <font weight="500" style="normal">Roboto-Medium.ttf</font>
28        <font weight="500" style="italic">Roboto-MediumItalic.ttf</font>
29        <font weight="900" style="normal">Roboto-Black.ttf</font>
30        <font weight="900" style="italic">Roboto-BlackItalic.ttf</font>
31        <font weight="700" style="normal">Roboto-Bold.ttf</font>
32        <font weight="700" style="italic">Roboto-BoldItalic.ttf</font>
33    </family>

The name attribute name="sans-serif" of family tag defined the value you can use in android:fontFamily.

The font tag define the corresponded font files.

In this case, you can ignore the source under <!-- fallback fonts -->, it's using for fonts' fallback logic.

Get class list for element with jQuery

Might this can help you too. I have used this function to get classes of childern element..

function getClickClicked(){
    var clickedElement=null;
    var classes = null;<--- this is array
    ELEMENT.on("click",function(e){//<-- where element can div,p span, or any id also a class
        clickedElement = $(e.target);
        classes = clickedElement.attr("class").split(" ");
        for(var i = 0; i<classes.length;i++){
            console.log(classes[i]);
        }
        e.preventDefault();
    });
}

In your case you want doler_ipsum class u can do like this now calsses[2];.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

if the problem still exists try to force changing the pass

Stop MySQL Server (on Linux):

/etc/init.d/mysql stop

Stop MySQL Server (on Mac OS X):

mysql.server stop

Start mysqld_safe daemon with --skip-grant-tables

mysqld_safe --skip-grant-tables &
mysql -u root

Setup new MySQL root user password

use mysql;
update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
flush privileges;
quit;

Stop MySQL Server (on Linux):

/etc/init.d/mysql stop

Stop MySQL Server (on Mac OS X):

mysql.server stop

Start MySQL server service and test to login by root:

mysql -u root -p

How to write header row with csv.DictWriter?

Another way to do this would be to add before adding lines in your output, the following line :

output.writerow(dict(zip(dr.fieldnames, dr.fieldnames)))

The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.

VBA, if a string contains a certain letter

Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.

If InStr(myString, "A") > 0 Then

InStr MSDN Website

For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.

Left(oldStr, InStr(oldStr, "A"))

Using Keras & Tensorflow with AMD GPU

Theano does have support for OpenCL but it is still in its early stages. Theano itself is not interested in OpenCL and relies on community support.

Most of the operations are already implemented and it is mostly a matter of tuning and optimizing the given operations.

To use the OpenCL backend you have to build libgpuarray yourself.

From personal experience I can tell you that you will get CPU performance if you are lucky. The memory allocation seems to be very naively implemented (therefore computation will be slow) and will crash when it runs out of memory. But I encourage you to try and maybe even optimize the code or help reporting bugs.

How to solve '...is a 'type', which is not valid in the given context'? (C#)

CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:

using (CERas.CERAS ceras = new CERas.CERAS())
{
    // call some method on ceras
}

If input value is blank, assign a value of "empty" with Javascript

If you're using pure JS you can simply do it like:

var input = document.getElementById('myInput');

if(input.value.length == 0)
    input.value = "Empty";

Here's a demo: http://jsfiddle.net/nYtm8/

How to filter object array based on attributes?

I use my ruleOut function for filtering objects based on specific unwanted property values. I understand that in your example you would like to use conditions instead of values, but my answer is valid for the question title, so I'd like to leave my method here.

function ruleOut(arr, filterObj, applyAllFilters=true) {    
    return arr.filter( row => {            
        for (var field in filterObj) {
            var val = row[field];
            if (val) {                    
                if (applyAllFilters && filterObj[field].indexOf(val) > -1) return false;                
                else if (!applyAllFilters) {                        
                    return filterObj[field].filter(function(filterValue){ 
                        return (val.indexOf(filterValue)>-1);
                    }).length == 0;                 
                }
            }
        }
        return true;
    });
}

Say you have a list of actors like this:

let actors = [
  {userName:"Mary", job:"star", language:"Turkish"},
  {userName:"John", job:"actor", language:"Turkish"},
  {userName:"Takis", job:"star", language:"Greek"},
  {userName:"Joe", job:"star", language:"Turkish"},
  {userName:"Bill", job:"star", language:"Turkish"}
];

and you would like to find all actors that are rated as Holywood stars, their nationality should not be one of 'English', 'Italian', 'Spanish', 'Greek', plus their name would not be one of 'Mary', 'Joe'. Bizzar example, I know! Anyway, with that set of conditions you would create the following object:

let unwantedFieldsFilter= { 
  userName: ['Mary', 'Joe'],    
  job: ['actor'],   
  language: ['English', 'Italian', 'Spanish', 'Greek']  
};

OK, now if you ruleOut(actors, unwantedFieldsFilter) you would only get

[{userName: "Bill", job: "star", language: "Turkish"}]

And Bill is your man, since his name is not one of 'Mary', 'Joe', his nationality is not included in ['English', 'Italian', 'Spanish', 'Greek'] plus he is a Star!

There is one option in my method, that is applyAllFilters and is true by default. If you would try to ruleOut with this param set as false, that would work as an 'OR' filtering instead of 'AND'. Example: ruleOut(actors, {job:["actor"], language:["Italian"]}, false) would get you everyone that is not an actor or Italian:

[{userName: "Mary", job: "star", language: "Turkish"},
{userName: "Takis", job: "star", language: "Greek"},
{userName: "Joe", job: "star", language: "Turkish"},
{userName: "Bill", job: "star", language: "Turkish"}]

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

How can I use ":" as an AWK field separator?

"-F" is a command line argument, not AWK syntax. Try:

 echo "1: " | awk -F  ":" '/1/ {print $1}'

How to throw an exception in C?

If you write code with Happy path design pattern (i.e. for embedded device) you may simulate exception error processing (aka deffering or finally emulation) with operator "goto".

int process(int port)
{
    int rc;
    int fd1;
    int fd2;

    fd1 = open("/dev/...", ...);
    if (fd1 == -1) {
      rc = -1;
      goto out;
    }

    fd2 = open("/dev/...", ...);
    if (fd2 == -1) {
      rc = -1;
      goto out;
    }

    // Do some with fd1 and fd2 for example write(f2, read(fd1))

    rc = 0;

   out:

    //if (rc != 0) {
        (void)close(fd1);
        (void)close(fd2);
    //}

    return rc;
}

It does not actually exception handler but it take you a way to handle error at fucntion exit.

P.S. You should be careful use goto only from same or more deep scopes and never jump variable declaration.

Checking if a key exists in a JS object

Use the in operator:

testArray = 'key1' in obj;

Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.

How to position the form in the center screen?

Using this Function u can define your won position

setBounds(500, 200, 647, 418);

Which Java library provides base64 encoding/decoding?

Guava also has Base64 (among other encodings and incredibly useful stuff)

Set transparent background using ImageMagick and commandline prompt

Yep. Had this same problem too. Here's the command I ran and it worked perfectly: convert transparent-img1.png transparent-img2.png transparent-img3.png -channel Alpha favicon.ico

Intent.putExtra List

you can do it in two ways using

  • Serializable

  • Parcelable.

This examle will show you how to implement it with serializable

class Customer implements Serializable
{
   // properties, getter setters & constructor
}

// This is your custom object
Customer customer = new Customer(name, address, zip);

Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);
startActivity(intent);

// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
    Customer customer = (Customer)extras.getSerializable("customer");
    // do something with the customer
}

Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.

Look at this.. This discussion will let you know which is much better way to implement it.

Thanks.

Get text from pressed button

Try to use:

String buttonText = ((Button)v).getText().toString();

How to display tables on mobile using Bootstrap?

After researching for almost 1 month i found the below code which is working very beautifully and 100% perfectly on my website. To check the preview how it is working you can check from the link. https://www.jobsedit.in/state-government-jobs/

CSS CODE-----

@media only screen and (max-width: 500px)  {
    .resp table  { 
        display: block ; 
    }   
    .resp th  { 
        position: absolute;
        top: -9999px;
        left: -9999px;
        display:block ;
    }   
     .resp tr { 
    border: 1px solid #ccc;
    display:block;
    }   
    .resp td  { 
        /* Behave  like a "row" */
        border: none;
        border-bottom: 1px solid #eee; 
        position: relative;
        width:100%;
        background-color:White;
        text-indent: 50%; 
        text-align:left;
        padding-left: 0px;
        display:block;      
    }
    .resp  td:nth-child(1)  {
        border: none;
        border-bottom: 1px solid #eee; 
        position: relative;
        font-size:20px;
        text-indent: 0%;
        text-align:center;
}   
    .resp td:before  { 
        /* Now like a table header */
        position: absolute;
        /* Top/left values mimic padding */
        top: 6px;
        left: 6px;
        width: 45%; 
        text-indent: 0%;
        text-align:left;
        white-space: nowrap;
        background-color:White;
        font-weight:bold;
    }
    /*
    Label the data
    */
    .resp td:nth-of-type(2):before  { content: attr(data-th) }
    .resp td:nth-of-type(3):before  { content: attr(data-th) }
    .resp td:nth-of-type(4):before  { content: attr(data-th) }
    .resp td:nth-of-type(5):before  { content: attr(data-th) }
    .resp td:nth-of-type(6):before  { content: attr(data-th) }
    .resp td:nth-of-type(7):before  { content: attr(data-th) }
    .resp td:nth-of-type(8):before  { content: attr(data-th) }
    .resp td:nth-of-type(9):before  { content: attr(data-th) }
    .resp td:nth-of-type(10):before  { content: attr(data-th) }
}

HTML CODE --

<table>
<tr>
<td data-th="Heading 1"></td>
<td data-th="Heading 2"></td>
<td data-th="Heading 3"></td>
<td data-th="Heading 4"></td>
<td data-th="Heading 5"></td>
</tr>
</table>

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

Why does visual studio 2012 not find my tests?

I had same symptoms, but under different circumstances.

I had to add one additional step to Peter Lamberg's solution — Clean your solution/project.

My unittest project targets x64. When I created the project it was originally targeting x86.

After switching to x64 all my unit tests disappeared.

I had to go to the Test Menu -> Test Setting -Default Processor Architecture -> x64.

They still didn't show up.

Did a build.

Still didn't show up.

Finally did a Clean

Then they showed up.

I find Clean Solution and Clean to be quite useful at getting the solutions to play ball when setting have changed. Sometimes I have to go to the extreme and delete the obj and bin directories and do a rebuild.

How to implement the Android ActionBar back button?

To enable the ActionBar back button you obviously need an ActionBar in your Activity. This is set by the theme you are using. You can set the theme for your Activity in the AndroidManfiest.xml. If you are using e.g the @android:style/Theme.NoTitleBar theme, you don't have an ActionBar. In this case the call to getActionBar() will return null. So make sure you have an ActionBar first.

The next step is to set the android:parentActivityName to the activity you want to navigate if you press the back button. This should be done in the AndroidManifest.xml too.

Now you can enable the back button in the onCreate method of your "child" activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Now you should implement the logic for the back button. You simply override the onOptionsItemSelected method in your "child" activity and check for the id of the back button which is android.R.id.home.

Now you can fire the method NavUtils.navigateUpFromSameTask(this); BUT if you don't have specified the android:parentActivityName in you AndroidManifest.xml this will crash your app.

Sometimes this is what you want because it is reminding you that you forgot "something". So if you want to prevent this, you can check if your activity has a parent using the getParentActivityIntent() method. If this returns null, you don't have specified the parent.

In this case you can fire the onBackPressed() method that does basically the same as if the user would press the back button on the device. A good implementation that never crashes your app would be:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            if (getParentActivityIntent() == null) {
                Log.i(TAG, "You have forgotten to specify the parentActivityName in the AndroidManifest!");
                onBackPressed();
            } else {
                NavUtils.navigateUpFromSameTask(this);
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Please notice that the animation that the user sees is different between NavUtils.navigateUpFromSameTask(this); and onBackPressed().

It is up to you which road you take, but I found the solution helpful, especially if you use a base class for all of your activities.

MySQL Sum() multiple columns

SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table

How can I return to a parent activity correctly?

A better way to achieve this is by using two things: call:

NavUtils.navigateUpFromSameTask(this);

Now, in order for this to work, you need to have your manifest file state that activity A has a parent activity B. The parent activity doesn't need anything. In version 4 and above you will get a nice back arrow with no additional effort (this can be done on lower versions as well with a little code, I'll put it below) You can set this data in the manifest->application tab in the GUI (scroll down to the parent activity name, and put it by hand)

Support node:

if you wish to support version below version 4, you need to include metadata as well. right click on the activity, add->meta data, name =android.support.PARENT_ACTIVITY and value = your.full.activity.name

to get the nice arrow in lower versions as well:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

please note you will need support library version 7 to get this all working, but it is well worth it!

Get Absolute Position of element within the window in wpf

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

How can I hide or encrypt JavaScript code?

While everyone will generally agree that Javascript encryption is a bad idea, there are a few small use cases where slowing down the attack is better than nothing. You can start with YUI Compressor (as @Ben Alpert) said, or JSMin, Uglify, or many more.

However, the main case in which I want to really 'hide stuff' is when I'm publishing an email address. Note, there is the problem of Chrome when you click on 'inspect element'. It will show your original code: every time. This is why obfuscation is generally regarded as being a better way to go.

On that note, I take a two pronged attack, purely to slow down spam bots. I Obfuscate/minify the js and then run it again through an encoder (again, this second step is completely pointless in chrome).

While not exactly a pure Javascript encoder, the best html encoder I have found is http://hivelogic.com/enkoder/. It will turn this:

<script type="text/javascript">
//<![CDATA[
<!--
var c=function(e) { var m="mail" + "to:webmaster";var a="somedomain"; e.href = m+"@"+a+".com";  
};
//-->
//]]>
</script>
<a href="#" onclick="return c(this);"><img src="images/email.png" /></a>

into this:

<script type="text/javascript">
//<![CDATA[
<!--
var x="function f(x){var i,o=\"\",ol=x.length,l=ol;while(x.charCodeAt(l/13)!" +
"=50){try{x+=x;l+=l;}catch(e){}}for(i=l-1;i>=0;i--){o+=x.charAt(i);}return o" +
".substr(0,ol);}f(\")87,\\\"meozp?410\\\\=220\\\\s-dvwggd130\\\\#-2o,V_PY420" +
"\\\\I\\\\\\\\_V[\\\\\\\\620\\\\o710\\\\RB\\\\\\\\610\\\\JAB620\\\\720\\\\n\\"+
"\\{530\\\\410\\\\WJJU010\\\\|>snnn|j5J(771\\\\p{}saa-.W)+T:``vk\\\"\\\\`<02" +
"0\\\\!610\\\\'Dr\\\\010\\\\630\\\\400\\\\620\\\\700\\\\\\\\\\\\N730\\\\,530" +
"\\\\2S16EF600\\\\;420\\\\9ZNONO1200\\\\/000\\\\`'7400\\\\%n\\\\!010\\\\hpr\\"+
"\\= -cn720\\\\a(ce230\\\\500\\\\f730\\\\i,`200\\\\630\\\\[YIR720\\\\]720\\\\"+
"r\\\\720\\\\h][P]@JHADY310\\\\t230\\\\G500\\\\VBT230\\\\200\\\\Clxhh{tzra/{" +
"g0M0$./Pgche%Z8i#p`v^600\\\\\\\\\\\\R730\\\\Q620\\\\030\\\\730\\\\100\\\\72" +
"0\\\\530\\\\700\\\\720\\\\M410\\\\N730\\\\r\\\\530\\\\400\\\\4420\\\\8OM771" +
"\\\\`4400\\\\$010\\\\t\\\\120\\\\230\\\\r\\\\610\\\\310\\\\530\\\\e~o120\\\\"+
"RfJjn\\\\020\\\\lZ\\\\\\\\CZEWCV771\\\\v5lnqf2R1ox771\\\\p\\\"\\\\tr\\\\220" +
"\\\\310\\\\420\\\\600\\\\OSG300\\\\700\\\\410\\\\320\\\\410\\\\120\\\\620\\" +
"\\q)5<: 0>+\\\"(f};o nruter};))++y(^)i(tAedoCrahc.x(edoCrahCmorf.gnirtS=+o;" +
"721=%y;++y)87<i(fi{)++i;l<i;0=i(rof;htgnel.x=l,\\\"\\\"=o,i rav{)y,x(f noit" +
"cnuf\")"                                                                     ;
while(x=eval(x));
//-->
//]]>
</script>

Maybe it's enough to slow down a few spam bots. I haven't had any spam come through using this (!yet).

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

Actual meaning of 'shell=True' in subprocess

let's assume you are using shell=False and providing the command as a list. And some malicious user tried injecting an 'rm' command. You will see, that 'rm' will be interpreted as an argument and effectively 'ls' will try to find a file called 'rm'

>>> subprocess.run(['ls','-ld','/home','rm','/etc/passwd'])
ls: rm: No such file or directory
-rw-r--r--    1 root     root          1172 May 28  2020 /etc/passwd
drwxr-xr-x    2 root     root          4096 May 29  2020 /home
CompletedProcess(args=['ls', '-ld', '/home', 'rm', '/etc/passwd'], returncode=1)

shell=False is not a secure by default, if you don't control the input properly. You can still execute dangerous commands.

>>> subprocess.run(['rm','-rf','/home'])
CompletedProcess(args=['rm', '-rf', '/home'], returncode=0)
>>> subprocess.run(['ls','-ld','/home'])
ls: /home: No such file or directory
CompletedProcess(args=['ls', '-ld', '/home'], returncode=1)
>>>

I am writing most of my applications in container environments, I know which shell is being invoked and i am not taking any user input.

So in my use case, I see no security risk. And it is much easier creating long string of commands. Hope I am not wrong.

Cannot get OpenCV to compile because of undefined references?

follow this tutorial. i ran the install-opencv.sh file in bash. its in the tutorial

read the example from openCV

CMakeLists.txt

cmake_minimum_required(VERSION 3.7)
project(openCVTest)
# cmake needs this line
cmake_minimum_required(VERSION 2.8)

# Define project name
project(opencv_example_project)

# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)

# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS "    version: ${OpenCV_VERSION}")
message(STATUS "    libraries: ${OpenCV_LIBS}")
message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")

if(CMAKE_VERSION VERSION_LESS "2.8.11")
    # Add OpenCV headers location to your include paths
    include_directories(${OpenCV_INCLUDE_DIRS})
endif()

# Declare the executable target built from your sources
add_executable(main main.cpp)

# Link your application with OpenCV libraries
target_link_libraries(main ${OpenCV_LIBS})

main.cpp

/**
 * @file LinearBlend.cpp
 * @brief Simple linear blender ( dst = alpha*src1 + beta*src2 )
 * @author OpenCV team
 */

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

using namespace cv;

/** Global Variables */
const int alpha_slider_max = 100;
int alpha_slider;
double alpha;
double beta;

/** Matrices to store images */
Mat src1;
Mat src2;
Mat dst;

//![on_trackbar]
/**
 * @function on_trackbar
 * @brief Callback for trackbar
 */
static void on_trackbar( int, void* )
{
    alpha = (double) alpha_slider/alpha_slider_max ;

    beta = ( 1.0 - alpha );

    addWeighted( src1, alpha, src2, beta, 0.0, dst);

    imshow( "Linear Blend", dst );
}
//![on_trackbar]

/**
 * @function main
 * @brief Main function
 */
int main( void )
{
    //![load]
    /// Read images ( both have to be of the same size and type )
    src1 = imread("../data/LinuxLogo.jpg");
    src2 = imread("../data/WindowsLogo.jpg");
    //![load]

    if( src1.empty() ) { printf("Error loading src1 \n"); return -1; }
    if( src2.empty() ) { printf("Error loading src2 \n"); return -1; }

    /// Initialize values
    alpha_slider = 0;

    //![window]
    namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
    //![window]

    //![create_trackbar]
    char TrackbarName[50];
    sprintf( TrackbarName, "Alpha x %d", alpha_slider_max );
    createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );
    //![create_trackbar]

    /// Show some stuff
    on_trackbar( alpha_slider, 0 );

    /// Wait until user press some key
    waitKey(0);
    return 0;
}

Tested in linux mint 17

How to set commands output as a variable in a batch file

Some notes and some tricks.

The 'official' way to assign result to a variable is with FOR /F though in the other answers is shown how a temporary file can be used also.

For command processing FOR command has two forms depending if the usebackq option is used. In the all examples below the whole output is used without splitting it.

FOR /f "tokens=* delims=" %%A in ('whoami') do @set "I-Am=%%A"
FOR /f "usebackq tokens=* delims=" %%A in (`whoami`) do @set "I-Am=%%A"

and if used directly in the console:

FOR /f "tokens=* delims=" %A in ('whoami') do set "I-Am=%A"
FOR /f "usebackq tokens=* delims=" %A in (`whoami`) do set "I-Am=%A"

%%A is a temporary variable available only on the FOR command context and is called token.The two forms can be useful in case when you are dealing with arguments containing specific quotes. It is especially useful with REPL interfaces of other languages or WMIC. Though in both cases the expression can be put in double quotes and it still be processed.

Here's an example with python (it is possible to transition the expression in the brackets on a separate line which is used for easier reading):

@echo off

for /f "tokens=* delims=" %%a in (
  '"python -c ""print("""Message from python""")"""'
) do (
    echo processed message from python: "%%a"
)

To use an assigned variable in the same FOR block check also the DELAYED EXPANSION

And some tricks

To save yourself from writing all the arguments for the FOR command you can use MACRO for assigning the result to variable:

@echo off

::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
   if %%n==2 (%\n%
      setlocal enableDelayedExpansion%\n%
      for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
         for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
      ) %\n%
   ) %\n%
) ^& set argv=,

::::: -------- ::::::::


:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%

the first argument to the macro is the command and the second the name of the variable we want to use and both are separated by , (comma). Though this is suitable only for straight forward scenarios.

If we want a similar macro for the console we can use DOSKEY

doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"
rem  -- example --
assign WHOAMI /LOGONID,my-id
echo %my-id%

DOSKEY does accept double quotes as enclosion for arguments so this also is useful for more simple scenarios.

FOR also works well with pipes which can be used for chaining commands (though it is not so good for assigning a variable.

hostname |for /f "tokens=* delims=" %%# in ('more') do @(ping %%#)

Which also can be beautified with macros:

@echo off
:: --- defining chain command macros ---
set "result-as-[arg]:=|for /f "tokens=* delims=" %%# in ('more') do @("
set "[arg]= %%#)"
:::  --------------------------  :::

::Example:
hostname %result-as-[arg]:% ping %[arg]%

And for completnes macros for the temp file approach (no doskey definition ,but it also can be easy done.If you have a SSD this wont be so slow):

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1"
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

chcp %[[%code-page%]]%
echo ~~%code-page%~~

whoami %[[%its-me%]]%
echo ##%its-me%##

For /f with another macro:

::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

The shortest possible output from git log containing author and date

git log --pretty=format:"%H %an %ad"

use --date= to set a date format

git log --pretty=format:"%H %an %ad" --date=short

Why Response.Redirect causes System.Threading.ThreadAbortException?

Response.Redirect() throws an exception to abort the current request.

This KB article describes this behavior (also for the Request.End() and Server.Transfer() methods).

For Response.Redirect() there exists an overload:

Response.Redirect(String url, bool endResponse)

If you pass endResponse=false, then the exception is not thrown (but the runtime will continue processing the current request).

If endResponse=true (or if the other overload is used), the exception is thrown and the current request will immediately be terminated.

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

That's a simple one

UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);

Why does Git say my master branch is "already up to date" even though it is not?

I think your basic issue here is that you're misinterpreting and/or misunderstanding what git does and why it does it.

When you clone some other repository, git makes a copy of whatever is "over there". It also takes "their" branch labels, such as master, and makes a copy of that label whose "full name" in your git tree is (normally) remotes/origin/master (but in your case, remotes/upstream/master). Most of the time you get to omit the remotes/ part too, so you can refer to that original copy as upstream/master.

If you now make and commit some change(s) to some file(s), you're the only one with those changes. Meanwhile other people may use the original repository (from which you made your clone) to make other clones and change those clones. They are the only ones with their changes, of course. Eventually though, someone may have changes they send back to the original owner (via "push" or patches or whatever).

The git pull command is mostly just shorthand for git fetch followed by git merge. This is important because it means you need to understand what those two operations actually do.

The git fetch command says to go back to wherever you cloned from (or have otherwise set up as a place to fetch from) and find "new stuff someone else added or changed or removed". Those changes are copied over and applied to your copy of what you got from them earlier. They are not applied to your own work, only to theirs.

The git merge command is more complicated and is where you are going awry. What it does, oversimplified a bit, is compare "what you changed in your copy" to "changes you fetched from someone-else and thus got added to your-copy-of-the-someone-else's-work". If your changes and their changes don't seem to conflict, the merge operation mushes them together and gives you a "merge commit" that ties your development and their development together (though there is a very common "easy" case in which you have no changes and you get a "fast forward").

The situation you're encountering now is one in which you have made changes and committed them—nine times, in fact, hence the "ahead 9"—and they have made no changes. So, fetch dutifully fetches nothing, and then merge takes their lack-of-changes and also does nothing.

What you want is to look at, or maybe even "reset" to, "their" version of the code.

If you merely want to look at it, you can simply check out that version:

git checkout upstream/master

That tells git that you want to move the current directory to the branch whose full name is actually remotes/upstream/master. You'll see their code as of the last time you ran git fetch and got their latest code.

If you want to abandon all your own changes, what you need to do is change git's idea of which revision your label, master, should name. Currently it names your most recent commit. If you get back onto that branch:

git checkout master

then the git reset command will allow you to "move the label", as it were. The only remaining problem (assuming you're really ready to abandon everything you've don) is finding where the label should point.

git log will let you find the numeric names—those things like 7cfcb29—which are permanent (never changing) names, and there are a ridiculous number of other ways to name them, but in this case you just want the name upstream/master.

To move the label, wiping out your own changes (any that you have committed are actually recoverable for quite a while but it's a lot harder after this so be very sure):

git reset --hard upstream/master

The --hard tells git to wipe out what you have been doing, move the current branch label, and then check out the given commit.

It's not super-common to really want to git reset --hard and wipe out a bunch of work. A safer method (making it a lot easier to recover that work if you decide some of it was worthwhile after all) is to rename your existing branch:

git branch -m master bunchofhacks

and then make a new local branch named master that "tracks" (I don't really like this term as I think it confuses people but that's the git term :-) ) the origin (or upstream) master:

git branch -t master upstream/master

which you can then get yourself on with:

git checkout master

What the last three commands do (there's shortcuts to make it just two commands) is to change the name pasted on the existing label, then make a new label, then switch to it:

before doing anything:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "master"

after git branch -m:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

after git branch -t master upstream/master:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

Here C0 is the latest commit (a complete source tree) that you got when you first did your git clone. C1 through C9 are your commits.

Note that if you were to git checkout bunchofhacks and then git reset --hard HEAD^^, this would change the last picture to:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 -    "bunchofhacks"
                                                      \
                                                       \- C8 --- C9

The reason is that HEAD^^ names the revision two up from the head of the current branch (which just before the reset would be bunchofhacks), and reset --hard then moves the label. Commits C8 and C9 are now mostly invisible (you can use things like the reflog and git fsck to find them but it's no longer trivial). Your labels are yours to move however you like. The fetch command takes care of the ones that start with remotes/. It's conventional to match "yours" with "theirs" (so if they have a remotes/origin/mauve you'd name yours mauve too), but you can type in "theirs" whenever you want to name/see commits you got "from them". (Remember that "one commit" is an entire source tree. You can pick out one specific file from one commit, with git show for instance, if and when you want that.)

How to catch exception correctly from http.request()?

There are several ways to do this. Both are very simple. Each of the examples works great. You can copy it into your project and test it.

The first method is preferable, the second is a bit outdated, but so far it works too.

1) Solution 1

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators

// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: HttpClient, private product: ProductModule){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will get into catchError and catch them.
    getProducts(): Observable<ProductModule[]>{
        const url = 'YOUR URL HERE';
        return this.http.get<ProductModule[]>(url).pipe(
            tap((data: any) => {
                console.log(data);
            }),
            catchError((err) => {
                throw 'Error in source. Details: ' + err; // Use console.log(err) for detail
            })
        );
    }
}

2) Solution 2. It is old way but still works.

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: Http){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will to into catch section and catch error.
    getProducts(){
        const url = '';
        return this.http.get(url).map(
            (response: Response) => {
                const data = response.json();
                console.log(data);
                return data;
            }
        ).catch(
            (error: Response) => {
                console.log(error);
                return Observable.throw(error);
            }
        );
    }
}

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

I faced the same problem, even if I was working on my home wifi connection, without any proxy requirements.

My project was created at c:\users\<>\Workspace\Project\

When I went to above location and ran

mvn clean install

I got below error:

[ERROR] Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its de
endencies could not be resolved: Failed to read artifact descriptor for org.apa
he.maven.plugins:maven-clean-plugin:jar:2.5: Could not transfer artifact org.ap
che.maven.plugins:maven-clean-plugin:pom:2.5 from/to central (https://repo.mave
.apache.org/maven2)

It took me entire day to try ways and means to crack this, but the solution in my case, was damn simple.

I moved my project to non-user specific location, at E:\Workspace\Project\

This has done wonders for me!

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

Postgres: INSERT if does not exist already

The solution in simple, but not immediatly.
If you want use this instruction, you must make one change to the db:

ALTER USER user SET search_path to 'name_of_schema';

after these changes "INSERT" will work correctly.

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Even when you asked finally for the opposite, to reform 0s and 1s into Trues and Falses, however, I post an answer about how to transform falses and trues into ones and zeros (1s and 0s), for a whole dataframe, in a single line.

Example given

df <- structure(list(p1_1 = c(TRUE, FALSE, FALSE, NA, TRUE, FALSE, 
                NA), p1_2 = c(FALSE, TRUE, FALSE, NA, FALSE, NA, 
                TRUE), p1_3 = c(TRUE, 
                TRUE, FALSE, NA, NA, FALSE, TRUE), p1_4 = c(FALSE, NA, 
                FALSE,  FALSE, TRUE, FALSE, NA), p1_5 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_6 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_7 = c(TRUE, NA, 
                FALSE, TRUE, NA, FALSE, TRUE), p1_8 = c(FALSE, 
                FALSE, NA, FALSE, TRUE, FALSE, NA), p1_9 = c(TRUE, 
                FALSE,  NA, FALSE, FALSE, NA, TRUE), p1_10 = c(TRUE, 
                FALSE, NA, FALSE, FALSE, NA, TRUE), p1_11 = c(FALSE, 
                FALSE, NA, FALSE, NA, FALSE, TRUE)), .Names = 
                c("p1_1", "p1_2", "p1_3", "p1_4", "p1_5", "p1_6", 
                "p1_7", "p1_8", "p1_9", "p1_10", "p1_11"), row.names = 
                 c(NA, -7L), class = "data.frame")

   p1_1  p1_2  p1_3  p1_4  p1_5  p1_6  p1_7  p1_8  p1_9 p1_10 p1_11
1  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE
2 FALSE  TRUE  TRUE    NA    NA    NA    NA FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE    NA    NA    NA    NA
4    NA    NA    NA FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
5  TRUE FALSE    NA  TRUE FALSE FALSE    NA  TRUE FALSE FALSE    NA
6 FALSE    NA FALSE FALSE    NA    NA FALSE FALSE    NA    NA FALSE
7    NA  TRUE  TRUE    NA  TRUE  TRUE  TRUE    NA  TRUE  TRUE  TRUE

Then by running that: df * 1 all Falses and Trues are trasnformed into 1s and 0s. At least, this was happen in the R version that I have (R version 3.4.4 (2018-03-15) ).

> df*1
  p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1    1    0    1    0    1    1    1    0    1     1     0
2    0    1    1   NA   NA   NA   NA    0    0     0     0
3    0    0    0    0    0    0    0   NA   NA    NA    NA
4   NA   NA   NA    0    1    1    1    0    0     0     0
5    1    0   NA    1    0    0   NA    1    0     0    NA
6    0   NA    0    0   NA   NA    0    0   NA    NA     0
7   NA    1    1   NA    1    1    1   NA    1     1     1

I do not know if it a total "safe" command, under all different conditions / dfs.

How to identify object types in java

You want instanceof:

if (value instanceof Integer)

This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do

if (value.getClass() == Integer.class)

or

if (Integer.class.equals(value.getClass())

Use IntelliJ to generate class diagram

Now there is an official way to add "PlantUML integration" plugin to your JetBrains product.

Installation steps please refer: https://stackoverflow.com/a/53387418/5320704

vim line numbers - how to have them on by default?

in home directory you will find a file called ".vimrc" in that file add this code "set nu" and save and exit and open new vi file and you will find line numbers on that.

How to select all elements with a particular ID in jQuery?

$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls

Asyncio.gather vs asyncio.wait

A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.


I'll use this example to simulate a coroutine that will raise exceptions, sometimes -

import asyncio
import random


async def a_flaky_tsk(i):
    await asyncio.sleep(i)  # bit of fuzz to simulate a real-world example

    if i % 2 == 0:
        print(i, "ok")
    else:
        print(i, "crashed!")
        raise ValueError

coros = [a_flaky_tsk(i) for i in range(10)]

await asyncio.gather(*coros) outputs -

0 ok
1 crashed!
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
    asyncio.run(main())
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
    await asyncio.gather(*coros)
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

As you can see, the coros after index 1 never got to execute.


But await asyncio.wait(coros) continues to execute tasks, even if some of them fail -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

Ofcourse, this behavior can be changed for both by using -

asyncio.gather(..., return_exceptions=True)

or,

asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)


But it doesn't end here!

Notice: Task exception was never retrieved in the logs above.

asyncio.wait() won't re-raise exceptions from the child tasks until you await them individually. (The stacktrace in the logs are just messages, they cannot be caught!)

done, pending = await asyncio.wait(coros)
for tsk in done:
    try:
        await tsk
    except Exception as e:
        print("I caught:", repr(e))

Output -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()

On the other hand, to catch exceptions with asyncio.gather(), you must -

results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
    if isinstance(result_or_exc, Exception):
        print("I caught:", repr(result_or_exc))

(Same output as before)

How to force a web browser NOT to cache images

From my point of view, disable images caching is a bad idea. At all.

The root problem here is - how to force browser to update image, when it has been updated on a server side.

Again, from my personal point of view, the best solution is to disable direct access to images. Instead access images via server-side filter/servlet/other similar tools/services.

In my case it's a rest service, that returns image and attaches ETag in response. The service keeps hash of all files, if file is changed, hash is updated. It works perfectly in all modern browsers. Yes, it takes time to implement it, but it is worth it.

The only exception - are favicons. For some reasons, it does not work. I could not force browser to update its cache from server side. ETags, Cache Control, Expires, Pragma headers, nothing helped.

In this case, adding some random/version parameter into url, it seems, is the only solution.

How to serve an image using nodejs

You should use the express framework.

npm install express

and then

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);

and then the URL localhost:8080/images/logo.gif should work.

How to update and delete a cookie?

check this out A little framework: a complete cookies reader/writer with full Unicode support

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Select first and last row from grouped data

A different base R alternative would be to first order by id and stopSequence, split them based on id and for every id we select only the first and last index and subset the dataframe using those indices.

df[sapply(with(df, split(order(id, stopSequence), id)), function(x) 
                   c(x[1], x[length(x)])), ]


#  id stopId stopSequence
#1  1      a            1
#3  1      c            3
#5  2      b            1
#6  2      c            4
#8  3      b            1
#7  3      a            3

Or similar using by

df[unlist(with(df, by(order(id, stopSequence), id, function(x) 
                   c(x[1], x[length(x)])))), ]

how to get html content from a webview?

I would suggest instead of trying to extract the HTML from the WebView, you extract the HTML from the URL. By this, I mean using a third party library such as JSoup to traverse the HTML for you. The following code will get the HTML from a specific URL for you

public static String getHtml(String url) throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";

        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                response.getEntity().getContent()
            )
        );

        String line = null;
        while ((line = reader.readLine()) != null){
            result += line + "\n";
        }
        return result;
    }

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

Set inputType for an EditText Programmatically?

For Kotlin:

    val password = EditText(this)
    password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
    password.hint = "Password"

What do numbers using 0x notation mean?

It's a hexadecimal number.

0x6400 translates to 4*16^2 + 6*16^3 = 25600

Merge (with squash) all changes from another branch as a single commit

Found it! Merge command has a --squash option

git checkout master
git merge --squash WIP

at this point everything is merged, possibly conflicted, but not committed. So I can now:

git add .
git commit -m "Merged WIP"

How do I use .woff fonts for my website?

After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts subdirectory.

In CSS code:

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font.woff") format('woff');
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-bold.woff") format('woff');
    font-weight: bold;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-boldoblique.woff") format('woff');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-oblique.woff") format('woff');
    font-style: italic;
}

After having that definitions, you can just write, for example,

In HTML code:

<div class="mydiv">
    <b>this will be written with awesome-font-bold.woff</b>
    <br/>
    <b><i>this will be written with awesome-font-boldoblique.woff</i></b>
    <br/>
    <i>this will be written with awesome-font-oblique.woff</i>
    <br/>
    this will be written with awesome-font.woff
</div>

In CSS code:

.mydiv {
    font-family: myfont
}

The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.

HTML meta tag for content language

<meta name="language" content="Spanish">

This isn't defined in any specification (including the HTML5 draft)

<meta http-equiv="content-language" content="es">

This is a poor man's version of a real HTTP header and should really be expressed in the headers. For example:

Content-language: es
Content-type: text/html;charset=UTF-8

It says that the document is intended for Spanish language speakers (it doesn't, however mean the document is written in Spanish; it could, for example, be written in English as part of a language course for Spanish speakers).

From the spec:

The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.

If you want to state that a document is written in Spanish then use:

<html lang="es">

Change drive in git bash for windows

In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

iPad browser WIDTH & HEIGHT standard

There's no simple answer to this question. Apple's mobile version of WebKit, used in iPhones, iPod Touches, and iPads, will scale the page to fit the screen, at which point the user can zoom in and out freely.

That said, you can design your page to minimize the amount of zooming necessary. Your best bet is to make the width and height the same as the lower resolution of the iPad, since you don't know which way it's oriented; in other words, you would make your page 768x768, so that it will fit well on the iPad's screen whether it's oriented to be 1024x768 or 768x1024.

More importantly, you'd want to design your page with big controls with lots of space that are easy to hit with your thumbs - you could easily design a 768x768 page that was very cluttered and therefore required lots of zooming. To accomplish this, you'll likely want to divide your controls among a number of web pages.

On the other hand, it's not the most worthwhile pursuit. If while designing you find opportunities to make your page more "finger-friendly", then go for it...but the reality is that iPad users are very comfortable with moving around and zooming in and out of the page to get to things because it's necessary on most web sites. If anything, you probably want to design it so that it's conducive to this type of navigation.

Make boxes with relevant grouped data that can be easily double-tapped to focus on, and keep related controls close to each other. iPad users will most likely appreciate a page that facilitates the familiar zoom-and-pan navigation they're accustomed to more than they will a page that has fewer controls so that they don't have to.

IBOutlet and IBAction

An Outlet is a link from code to UI. If you want to show or hide an UI element, if you want to get the text of a textfield or enable or disable an element (or a hundred other things) you have to define an outlet of that object in the sources and link that outlet through the “interface object” to the UI element. After that you can use the outlet just like any other variable in your coding.

IBAction – a special method triggered by user-interface objects. Interface Builder recognizes them.

@interface Controller
{
  IBOutlet id textField; // links to TextField UI object
}

- (IBAction)doAction:(id)sender; // e.g. called when button pushed

For further information please refer Apple Docs

How to add an object to an ArrayList in Java

change Date to Object which is between parenthesis

Visual Studio Code open tab in new window

When I want to split the screens I usually do one of the following:

  1. open new window with: Ctrl+Shift+N
    and after that I drag the current file I want to the new window.
  2. on the File explorer - I hit Ctrl+Enter on the file I want - and then this file and the other file open together in the same screen but in split mode, so you can see the two files together. If the screen is wide enough this is not a bad solution at all that you can get used to.

Inserting data to table (mysqli insert)

In mysqli_query(first parameter should be connection,your sql statement) so

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');

but best practice is

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);

Razor-based view doesn't see referenced assemblies

Try adding the namespace your MyClasses is in to the web.config under

<pages> <namespaces></namespaces> </pages>

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Install Entity Framework in each project (Ex: In Web, In Class Libraries) from NuGet Package Manager orelse Open Tools - Nuget Package Manager - Package Manager Console and use Install-Package EntityFramework to install the Entity Framework.

Don't need to add the below code in every config file. By default it will be added in the project where the database is called through Entity Framework.

<entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework>

How to set the thumbnail image on HTML5 video?

If you want a video first frame as a thumbnail, than you can use

Add #t=0.1 to your video source, like below

<video width="320" height="240" controls>
  <source src="video.mp4#t=0.1" type="video/mp4">
</video>

NOTE: make sure about your video type(ex: mp4, ogg, webm etc)

How can I temporarily disable a foreign key constraint in MySQL?

For me just SET FOREIGN_KEY_CHECKS=0; wasn't enough. I was still having a com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException.

I had to add ALTER TABLE myTable DISABLE KEYS;.

So:

SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE myTable DISABLE KEYS;
DELETE FROM myTable;
ALTER TABLE myTable ENABLE KEYS;
SET FOREIGN_KEY_CHECKS=1;

What are the main differences between JWT and OAuth authentication?

find the main differences between JWT & OAuth

  1. OAuth 2.0 defines a protocol & JWT defines a token format.

  2. OAuth can use either JWT as a token format or access token which is a bearer token.

  3. OpenID connect mostly use JWT as a token format.

diff current working copy of a file with another branch's committed copy

You're trying to compare your working tree with a particular branch name, so you want this:

git diff master -- foo

Which is from this form of git-diff (see the git-diff manpage)

   git diff [--options] <commit> [--] [<path>...]
       This form is to view the changes you have in your working tree
       relative to the named <commit>. You can use HEAD to compare it with
       the latest commit, or a branch name to compare with the tip of a
       different branch.

FYI, there is also a --cached (aka --staged) option for viewing the diff of what you've staged, rather than everything in your working tree:

   git diff [--options] --cached [<commit>] [--] [<path>...]
       This form is to view the changes you staged for the next commit
       relative to the named <commit>.
       ...
       --staged is a synonym of --cached.

How to find reason of failed Build without any error or warning

What solved it for me was deleting the .vs folder from the root of the solution and restarting Visual Studio.

Also maybe important to say that even though the errors were not showing in the Error List pane, they were still present in the Output from the Build.

Request Permission for Camera and Library in iOS 10 - Info.plist

File: Info.plist

For Camera:

<key>NSCameraUsageDescription</key>
<string>You can take photos to document your job.</string>

For Photo Library, you will want this one to allow app user to browse the photo library.

<key>NSPhotoLibraryUsageDescription</key>
<string>You can select photos to attach to reports.</string>

Node.js check if file exists

You can use fs.stat to check if target is a file or directory and you can use fs.access to check if you can write/read/execute the file. (remember to use path.resolve to get full path for the target)

Documentation:

Full example (TypeScript)

import * as fs from 'fs';
import * as path from 'path';

const targetPath = path.resolve(process.argv[2]);

function statExists(checkPath): Promise<fs.Stats> {
  return new Promise((resolve) => {
    fs.stat(checkPath, (err, result) => {
      if (err) {
        return resolve(undefined);
      }

      return resolve(result);
    });
  });
}

function checkAccess(checkPath: string, mode: number = fs.constants.F_OK): Promise<boolean> {
  return new Promise((resolve) => {
    fs.access(checkPath, mode, (err) => {
      resolve(!err);
    });
  });
}

(async function () {
  const result = await statExists(targetPath);
  const accessResult = await checkAccess(targetPath, fs.constants.F_OK);
  const readResult = await checkAccess(targetPath, fs.constants.R_OK);
  const writeResult = await checkAccess(targetPath, fs.constants.W_OK);
  const executeResult = await checkAccess(targetPath, fs.constants.X_OK);
  const allAccessResult = await checkAccess(targetPath, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);

  if (result) {
    console.group('stat');
    console.log('isFile: ', result.isFile());
    console.log('isDir: ', result.isDirectory());
    console.groupEnd();
  }
  else {
    console.log('file/dir does not exist');
  }

  console.group('access');
  console.log('access:', accessResult);
  console.log('read access:', readResult);
  console.log('write access:', writeResult);
  console.log('execute access:', executeResult);
  console.log('all (combined) access:', allAccessResult);
  console.groupEnd();

  process.exit(0);
}());

How to trigger the onclick event of a marker on a Google Maps V3?

For future Googlers, If you get an error similar below after you trigger click for a polygon

"Uncaught TypeError: Cannot read property 'vertex' of undefined"

then try the code below

google.maps.event.trigger(polygon, "click", {});

Move view with keyboard using Swift

Swift 3 code

var activeField: UITextField?

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}

func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if (self.activeField?.frame.origin.y)! >= keyboardSize.height {
            self.view.frame.origin.y = keyboardSize.height - (self.activeField?.frame.origin.y)!
        } else {
            self.view.frame.origin.y = 0
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    self.view.frame.origin.y = 0
}

sendKeys() in Selenium web driver

Try this code:

WebElement userName = pathfinderdriver.switchTo().activeElement();
userName.sendKeys(Keys.TAB);

What is the correct way to restore a deleted file from SVN?

With Tortoise SVN:

If you haven't committed your changes yet, you can do a revert on the parent folder where you deleted the file or directory.

If you have already committed the deleted file, then you can use the repository browser, change to the revision where the file still existed and then use the command Copy to... from the context menu. Enter the path to your working copy as the target and the deleted file will be copied from the repository to your working copy.

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

How do I get the last inserted ID of a MySQL table in PHP?

It's ok to use mysql_insert_id(), but there is one specific note about using it, you must call it after executed INSERT query, means in the same script session. If you use it otherwise it wouldn't work correctly.

Whitespace Matching Regex - Java

For Java (not php, not javascript, not anyother):

txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")

sed one-liner to convert all uppercase to lowercase?

short, sweet and you don't even need redirection :-)

perl -p -i -e 'tr/A-Z/a-z/' file

How to check if a python module exists without importing it

You can also use importlib directly

import importlib

try:
    importlib.import_module(module_name)
except ImportError:
    # Handle error

"Items collection must be empty before using ItemsSource."

Beware of typos! I had the following

<TreeView ItemsSource="{Binding MyCollection}">
    <TreeView.Resources>
        ...
    </TreeView.Resouces>>
</TreeView>

(Notice the tailing >, which is interpreted as content, so you're setting twice the content... Took me a while :)

Is it possible to overwrite a function in PHP

I would include all functions of one case in an include file, and the others in another include.

For instance simple.inc would contain function boofoo() { simple } and really.inc would contain function boofoo() { really }

It helps the readability / maintenance of your program, having all functions of the same kind in the same inc.

Then at the top of your main module

  if ($_GET['foolevel'] == 10) {
    include "really.inc";
  }
  else {
    include "simple.inc";
  }

is it possible to evenly distribute buttons across the width of an android linearlayout

If you want the 3 buttons to have a fixed width and be evenly distributed across the width of the layout... why not use constraintLayout?

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <Button
            android:id="@+id/btnOne"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:width="120dip"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@id/btnTwo">
            
        </Button>

        <Button
            android:id="@+id/btnTwo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:width="120dip"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/btnThree"
            app:layout_constraintStart_toEndOf="@id/btnOne"></Button>


        <Button
            android:id="@+id/btnThree"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:width="120dip"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toEndOf="@id/btnTwo"
            app:layout_constraintEnd_toEndOf="parent">
            
        </Button>

</androidx.constraintlayout.widget.ConstraintLayout>

Checking whether the pip is installed?

$ which pip

or

 $ pip -V 

execute this command into your terminal. It should display the location of executable file eg. /usr/local/bin/pip and the second command will display the version if the pip is installed correctly.

comparing elements of the same array in java

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            System.out.println(a[i] + " not the same with  " + a[k + 1] + "\n");
        }
    }
}

You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.

How to Allow Remote Access to PostgreSQL database

This is a complementary answer for the specific case of you using AWS cloud computing (either EC2 or RDS machines).

Besides doing everything proposed above, when using AWS cloud computing you will need to set you inbound rules in a way that let you access to the ports. Please check this post, which is valid for EC2 and RDS.

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 drop in and out of the PHP context using the <?php and ?> tags. For example...

<?php
$array = array(1, 2, 3, 4);
?>

<table>
<thead><tr><th>Number</th></tr></thead>
<tbody>
<?php foreach ($array as $num) : ?>
<tr><td><?= htmlspecialchars($num) ?></td></tr>
<?php endforeach ?>
</tbody>
</table>

Also see Alternative syntax for control structures

Java - What does "\n" mean?

Its is a new line

Escape Sequences
Escape Sequence Description
\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a formfeed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

http://docs.oracle.com/javase/tutorial/java/data/characters.html

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

I know its very late but I think it may help someone in resolving his issue.

In my case It was occurring because compileSdkVersion and targetSdkVersion was set to 29 while when I check my SDK Manager, It was showing that package is partially installed. Whereas SDK version 28 was completely installed. I changed my compileSdkVersion and targetSdkVersion to 28 along with support libraries.

Earlier: compileSdkVersion 29 targetSdkVersion 29 implementation 'com.android.support:appcompat-v7:29.+' implementation 'com.android.support:design:29.+'

After Modification: compileSdkVersion 28 targetSdkVersion 28 implementation 'com.android.support:appcompat-v7:28.+' implementation 'com.android.support:design:28.+'

It worked like a charm after applying these changes.

Case Insensitive String comp in C

There is no function that does this in the C standard. Unix systems that comply with POSIX are required to have strcasecmp in the header strings.h; Microsoft systems have stricmp. To be on the portable side, write your own:

int strcicmp(char const *a, char const *b)
{
    for (;; a++, b++) {
        int d = tolower((unsigned char)*a) - tolower((unsigned char)*b);
        if (d != 0 || !*a)
            return d;
    }
}

But note that none of these solutions will work with UTF-8 strings, only ASCII ones.

Get current URL path in PHP

You want $_SERVER['REQUEST_URI']. From the docs:

'REQUEST_URI'

The URI which was given in order to access this page; for instance, '/index.html'.

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Use preventDefault() to stop the event of submit button and in ajax call success submit the form using submit():

$('#btnSave').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;    
    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert("Done");
                $(element).closest("form").submit(); //<------------ submit form
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

jQuery - adding elements into an array

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

How should a model be structured in MVC?

In my case I have a database class that handle all the direct database interaction such as querying, fetching, and such. So if I had to change my database from MySQL to PostgreSQL there won't be any problem. So adding that extra layer can be useful.

Each table can have its own class and have its specific methods, but to actually get the data, it lets the database class handle it:

File Database.php

class Database {
    private static $connection;
    private static $current_query;
    ...

    public static function query($sql) {
        if (!self::$connection){
            self::open_connection();
        }
        self::$current_query = $sql;
        $result = mysql_query($sql,self::$connection);

        if (!$result){
            self::close_connection();
            // throw custom error
            // The query failed for some reason. here is query :: self::$current_query
            $error = new Error(2,"There is an Error in the query.\n<b>Query:</b>\n{$sql}\n");
            $error->handleError();
        }
        return $result;
    }
 ....

    public static function find_by_sql($sql){
        if (!is_string($sql))
            return false;

        $result_set = self::query($sql);
        $obj_arr = array();
        while ($row = self::fetch_array($result_set))
        {
            $obj_arr[] = self::instantiate($row);
        }
        return $obj_arr;
    }
}

Table object classL

class DomainPeer extends Database {

    public static function getDomainInfoList() {
        $sql = 'SELECT ';
        $sql .='d.`id`,';
        $sql .='d.`name`,';
        $sql .='d.`shortName`,';
        $sql .='d.`created_at`,';
        $sql .='d.`updated_at`,';
        $sql .='count(q.id) as queries ';
        $sql .='FROM `domains` d ';
        $sql .='LEFT JOIN queries q on q.domainId = d.id ';
        $sql .='GROUP BY d.id';
        return self::find_by_sql($sql);
    }

    ....
}

I hope this example helps you create a good structure.

SET versus SELECT when assigning variables?

Aside from the one being ANSI and speed etc., there is a very important difference that always matters to me; more than ANSI and speed. The number of bugs I have fixed due to this important overlook is large. I look for this during code reviews all the time.

-- Arrange
create table Employee (EmployeeId int);
insert into dbo.Employee values (1);
insert into dbo.Employee values (2);
insert into dbo.Employee values (3);

-- Act
declare @employeeId int;
select @employeeId = e.EmployeeId from dbo.Employee e;

-- Assert
-- This will print 3, the last EmployeeId from the query (an arbitrary value)
-- Almost always, this is not what the developer was intending. 
print @employeeId; 

Almost always, that is not what the developer is intending. In the above, the query is straight forward but I have seen queries that are quite complex and figuring out whether it will return a single value or not, is not trivial. The query is often more complex than this and by chance it has been returning single value. During developer testing all is fine. But this is like a ticking bomb and will cause issues when the query returns multiple results. Why? Because it will simply assign the last value to the variable.

Now let's try the same thing with SET:

 -- Act
 set @employeeId = (select e.EmployeeId from dbo.Employee e);

You will receive an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

That is amazing and very important because why would you want to assign some trivial "last item in result" to the @employeeId. With select you will never get any error and you will spend minutes, hours debugging.

Perhaps, you are looking for a single Id and SET will force you to fix your query. Thus you may do something like:

-- Act
-- Notice the where clause
set @employeeId = (select e.EmployeeId from dbo.Employee e where e.EmployeeId = 1);
print @employeeId;

Cleanup

drop table Employee;

In conclusion, use:

  • SET: When you want to assign a single value to a variable and your variable is for a single value.
  • SELECT: When you want to assign multiple values to a variable. The variable may be a table, temp table or table variable etc.

JavaScript variable assignments from tuples

Unfortunately you can't use that tuple assignment syntax in (ECMA|Java)Script.

EDIT: Someone linked to Mozilla/JS 1.7 - this wouldn't work cross-browser but if that is not required then there's your answer.

How to check if a variable is an integer or a string?

if you want to check what it is:

>>>isinstance(1,str)
False
>>>isinstance('stuff',str)
True
>>>isinstance(1,int)
True
>>>isinstance('stuff',int)
False

if you want to get ints from raw_input

>>>x=raw_input('enter thing:')
enter thing: 3
>>>try: x = int(x)
   except: pass

>>>isinstance(x,int)
True

SQL Server - How to lock a table until a stored procedure finishes

Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

change figure size and figure format in matplotlib

The first part (setting the output size explictly) isn't too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()

But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick's convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)

JavaScript Object Id

Actually, you don't need to modify the object prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.

var __next_objid=1;
function objectId(obj) {
    if (obj==null) return null;
    if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
    return obj.__obj_id;
}

How do you move a file?

In TortoiseSVN right click somewhere and go TortoiseSVN > Repo Browser open the repository.

All you then have to do is drag and drop the file from one folder to the where you want it. It'll ask you to add a commit message and it defaults it to "Moved file/folder remotely"

How to edit log message already committed in Subversion?

Essentially you have to have admin rights (directly or indirectly) to the repository to do this. You can either configure the repository to allow all users to do this, or you can modify the log message directly on the server.

See this part of the Subversion FAQ (emphasis mine):

Log messages are kept in the repository as properties attached to each revision. By default, the log message property (svn:log) cannot be edited once it is committed. That is because changes to revision properties (of which svn:log is one) cause the property's previous value to be permanently discarded, and Subversion tries to prevent you from doing this accidentally. However, there are a couple of ways to get Subversion to change a revision property.

The first way is for the repository administrator to enable revision property modifications. This is done by creating a hook called "pre-revprop-change" (see this section in the Subversion book for more details about how to do this). The "pre-revprop-change" hook has access to the old log message before it is changed, so it can preserve it in some way (for example, by sending an email). Once revision property modifications are enabled, you can change a revision's log message by passing the --revprop switch to svn propedit or svn propset, like either one of these:

$svn propedit -r N --revprop svn:log URL 
$svn propset -r N --revprop svn:log "new log message" URL 

where N is the revision number whose log message you wish to change, and URL is the location of the repository. If you run this command from within a working copy, you can leave off the URL.

The second way of changing a log message is to use svnadmin setlog. This must be done by referring to the repository's location on the filesystem. You cannot modify a remote repository using this command.

$ svnadmin setlog REPOS_PATH -r N FILE

where REPOS_PATH is the repository location, N is the revision number whose log message you wish to change, and FILE is a file containing the new log message. If the "pre-revprop-change" hook is not in place (or you want to bypass the hook script for some reason), you can also use the --bypass-hooks option. However, if you decide to use this option, be very careful. You may be bypassing such things as email notifications of the change, or backup systems that keep track of revision properties.

How can I validate google reCAPTCHA v2 using javascript/jQuery?

Use this to validate google captcha with simple javascript.

This code at the html body:

<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />

This code put at head section on call get_action(this) method form button:

function get_action(form) 
{
    var v = grecaptcha.getResponse();
    if(v.length == 0)
    {
        document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
        return false;
    }
    else
    {
        document.getElementById('captcha').innerHTML="Captcha completed";
        return true; 
    }
}

Setting Django up to use MySQL

Follow the given steps in order to setup it up to use MySQL database:

1) Install MySQL Database Connector :

    sudo apt-get install libmysqlclient-dev

2) Install the mysqlclient library :

    pip install mysqlclient

3) Install MySQL server, with the following command :

    sudo apt-get install mysql-server

4) Create the Database :

    i) Verify that the MySQL service is running:

        systemctl status mysql.service

    ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :  

        mysql -u db_user -p


    iii) CREATE DATABASE db_name;

    iv) Exit MySQL server, press CTRL + D.

5) Add the MySQL Database Connection to your Application:

    i) Navigate to the settings.py file and replace the current DATABASES lines with the following:

        # Database
        # https://docs.djangoproject.com/en/2.0/ref/settings/#databases

        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'OPTIONS': {
                    'read_default_file': '/etc/mysql/my.cnf',
                },
            }
        }
        ...

    ii) Next, let’s edit the config file so that it has your MySQL credentials. Use vi as sudo to edit the file and add the following information:

        sudo vi /etc/mysql/my.cnf

        database = db_name
        user = db_user
        password = db_password
        default-character-set = utf8

6) Once the file has been edited, we need to restart MySQL for the changes to take effect :

    systemctl daemon-reload

    systemctl restart mysql

7) Test MySQL Connection to Application:

    python manage.py runserver your-server-ip:8000

How to remove line breaks from a file in Java?

You can use generic methods to replace any char with any char.

public static void removeWithAnyChar(String str, char replceChar,
        char replaceWith) {
    char chrs[] = str.toCharArray();
    int i = 0;
    while (i < chrs.length) {

        if (chrs[i] == replceChar) {
            chrs[i] = replaceWith;
        }
        i++;
    }

}

What's an easy way to read random line from a file in Unix command line?

This is simple.

cat file.txt | shuf -n 1

Granted this is just a tad slower than the "shuf -n 1 file.txt" on its own.

How is TeamViewer so fast?

The most fundamental thing here probably is that you don't want to transmit static images but only changes to the images, which essentially is analogous to video stream.

My best guess is some very efficient (and heavily specialized and optimized) motion compensation algorithm, because most of the actual change in generic desktop usage is linear movement of elements (scrolling text, moving windows, etc. opposed to transformation of elements).

The DirectX 3D performance of 1 FPS seems to confirm my guess to some extent.

Groovy built-in REST/HTTP client?

The simplest one got to be:

def html = "http://google.com".toURL().text

C# - Winforms - Global Variables

yes you can by using static class. like this:

static class Global
{
    private static string _globalVar = "";

    public static string GlobalVar
    {
        get { return _globalVar; }
        set { _globalVar = value; }
    }
}

and for using any where you can write:

GlobalClass.GlobalVar = "any string value"

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

How to make the background DIV only transparent using CSS

Just do not include a background color for that div and it will be transparent.

What's the difference between KeyDown and KeyPress in .NET?

The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

You will want to use a CONVERT() statement.

Try the following;

SELECT CONVERT(VARCHAR(10), SA.[RequestStartDate], 103) as 'Service Start Date', CONVERT(VARCHAR(10), SA.[RequestEndDate], 103) as 'Service End Date', FROM (......) SA WHERE.....

See MSDN Cast and Convert for more information.

Add Whatsapp function to website, like sms, tel

I just posted an answer on a thread similiar to this here https://stackoverflow.com/a/43357241/3958617

The approach with:

<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>

and with

<a href="intent://send/0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">whatsapp</a>

Only works if the person who clicked on your link have your number on their contact list.

Since not everybody will have it, the other solution is to use Whatsapp API like this:

<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

int[] and int* are represented the same way, except int[] allocates (IIRC).

ap is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.

when you try to access it (x = *ap), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.

Does Android keep the .apk files? if so where?

Preinstalled applications are in /system/app folder. User installed applications are in /data/app. I guess you can't access unless you have a rooted phone. I don't have a rooted phone here but try this code out:

public class Testing extends Activity {
    private static final String TAG = "TEST";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        File appsDir = new File("/data/app");

        String[] files = appsDir.list();

        for (int i = 0 ; i < files.length ; i++ ) {
            Log.d(TAG, "File: "+files[i]);

        }
    }

It does lists the apks in my rooted htc magic and in the emu.

Confirm password validation in Angular 6

I am using angular 6 and I have been searching on best way to match password and confirm password. This can also be used to match any two inputs in a form. I used Angular Directives. I have been wanting to use them

ng g d compare-validators --spec false and i will be added in your module. Below is the directive

import { Directive, Input } from '@angular/core';
import { Validator, NG_VALIDATORS, AbstractControl, ValidationErrors } from '@angular/forms';
import { Subscription } from 'rxjs';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[compare]',
  providers: [{ provide: NG_VALIDATORS, useExisting: CompareValidatorDirective, multi: true}]
})
export class CompareValidatorDirective implements Validator {
  // tslint:disable-next-line:no-input-rename
  @Input('compare') controlNameToCompare;

  validate(c: AbstractControl): ValidationErrors | null {
    if (c.value.length < 6 || c.value === null) {
      return null;
    }
    const controlToCompare = c.root.get(this.controlNameToCompare);

    if (controlToCompare) {
      const subscription: Subscription = controlToCompare.valueChanges.subscribe(() => {
        c.updateValueAndValidity();
        subscription.unsubscribe();
      });
    }

    return controlToCompare && controlToCompare.value !== c.value ? {'compare': true } : null;
  }

}

Now in your component

<div class="col-md-6">
              <div class="form-group">
                <label class="bmd-label-floating">Password</label>
                <input type="password" class="form-control" formControlName="usrpass" [ngClass]="{ 'is-invalid': submitAttempt && f.usrpass.errors }">
                <div *ngIf="submitAttempt && signupForm.controls['usrpass'].errors" class="invalid-feedback">
                  <div *ngIf="signupForm.controls['usrpass'].errors.required">Your password is required</div>
                  <div *ngIf="signupForm.controls['usrpass'].errors.minlength">Password must be at least 6 characters</div>
                </div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label class="bmd-label-floating">Confirm Password</label>
                <input type="password" class="form-control" formControlName="confirmpass" compare = "usrpass"
                [ngClass]="{ 'is-invalid': submitAttempt && f.confirmpass.errors }">
                <div *ngIf="submitAttempt && signupForm.controls['confirmpass'].errors" class="invalid-feedback">
                  <div *ngIf="signupForm.controls['confirmpass'].errors.required">Your confirm password is required</div>
                  <div *ngIf="signupForm.controls['confirmpass'].errors.minlength">Password must be at least 6 characters</div>
                  <div *ngIf="signupForm.controls['confirmpass'].errors['compare']">Confirm password and Password dont match</div>
                </div>
              </div>
            </div>

I hope this one helps

How to use GROUP BY to concatenate strings in SQL Server?

didn't see any cross apply answers, also no need for xml extraction. Here is a slightly different version of what Kevin Fairchild wrote. It's faster and easier to use in more complex queries:

   select T.ID
,MAX(X.cl) NameValues
 from #YourTable T
 CROSS APPLY 
 (select STUFF((
    SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX))
    FROM #YourTable 
    WHERE (ID = T.ID) 
    FOR XML PATH(''))
  ,1,2,'')  [cl]) X
  GROUP BY T.ID

How to install Python packages from the tar.gz file without using pip install

You may use pip for that without using the network. See in the docs (search for "Install a particular source archive file"). Any of those should work:

pip install relative_path_to_seaborn.tar.gz    
pip install absolute_path_to_seaborn.tar.gz    
pip install file:///absolute_path_to_seaborn.tar.gz    

Or you may uncompress the archive and use setup.py directly with either pip or python:

cd directory_containing_tar.gz
tar -xvzf seaborn-0.10.1.tar.gz
pip install seaborn-0.10.1
python setup.py install

Of course, you should also download required packages and install them the same way before you proceed.

How many files can I put in a directory?

I'm working on a similar problem right now. We have a hierarchichal directory structure and use image ids as filenames. For example, an image with id=1234567 is placed in

..../45/67/1234567_<...>.jpg

using last 4 digits to determine where the file goes.

With a few thousand images, you could use a one-level hierarchy. Our sysadmin suggested no more than couple of thousand files in any given directory (ext3) for efficiency / backup / whatever other reasons he had in mind.

Convert JavaScript String to be all lower case?

Note that the function will ONLY work on STRING objects.

For instance, I was consuming a plugin, and was confused why I was getting a "extension.tolowercase is not a function" JS error.

 onChange: function(file, extension)
    {
      alert("extension.toLowerCase()=>" + extension.toLowerCase() + "<=");

Which produced the error "extension.toLowerCase is not a function" So I tried this piece of code, which revealed the problem!

alert("(typeof extension)=>" + (typeof extension) + "<=");;

The output was"(typeof extension)=>object<=" - so AhHa, I was NOT getting a string var for my input. The fix is straight forward though - just force the darn thing into a String!:

var extension = String(extension);

After the cast, the extension.toLowerCase() function worked fine.

Android Studio doesn't see device

I have done numerous ways of handling that issue. Here is the flavor of what you need to follow step by step. I hope it would help you out.

Step 1: Make sure your device is enabled for development.

Step 2: Before you plug your device to PC, make sure you select USB Connection method.

Step 3: When you plug the phone in, you are given options for the USB Connection method, select Internet connection. Make sure you have connected to the Internet.

Step 4: Run the app in the Android Studio, it will ask you to authorize the device for development, and select YES.

Step 5: Run the application via Android Studio and choose the device, not emulator, and BINGO! Welcome to Android development board.

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

In [1]: 59**3*61**4*2*3*5*7*3*5*7
Out[1]: 62702371781194950
In [2]: _ % 61**4
Out[2]: 0

Transposing a 1D NumPy array

To 'transpose' a 1d array to a 2d column, you can use numpy.vstack:

>>> numpy.vstack(numpy.array([1,2,3]))
array([[1],
       [2],
       [3]])

It also works for vanilla lists:

>>> numpy.vstack([1,2,3])
array([[1],
       [2],
       [3]])

How to select option in drop down protractorjs e2e tests

Here's how I did it:

$('select').click();
$('select option=["' + optionInputFromFunction + '"]').click();
// This looks useless but it slows down the click event
// long enough to register a change in Angular.
browser.actions().mouseDown().mouseUp().perform();

How to convert DateTime? to DateTime

DateTime UpdatedTime = _objHotelPackageOrder.HasValue ? _objHotelPackageOrder.UpdatedDate.Value : DateTime.Now;

Using Java generics for JPA findAll() query with WHERE clause

Hat tip to Adam Bien if you don't want to use createQuery with a String and want type safety:

 @PersistenceContext
 EntityManager em;

 public List<ConfigurationEntry> allEntries() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class);
        Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class);
        CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry);
        TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all);
        return allQuery.getResultList();
 }

http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as

How do you run JavaScript script through the Terminal?

Use node.js for that, here is example how to install node by using brew on mac:

brew update && install node

Then run your program by typing node filename.js, and you can use console.log() for output.

How can I combine hashes in Perl?

Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)


Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.

If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:

my %new_hash = %hash1; # make a copy; leave %hash1 alone

foreach my $key2 ( keys %hash2 )
    {
    if( exists $new_hash{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $new_hash{$key2} = $hash2{$key2};
        }
    }

If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.

foreach my $key2 ( keys %hash2 )
    {
    if( exists $hash1{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $hash1{$key2} = $hash2{$key2};
        }
    }

If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:

@hash1{ keys %hash2 } = values %hash2;

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

How to enable or disable an anchor using jQuery?

Selected Answer is not good.

Use pointer-events CSS style. (As Rashad Annara suggested)

See MDN https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events. Its supported in most browsers.

Simple adding "disabled" attribute to anchor will do the job if you have global CSS rule like following:

a[disabled], a[disabled]:hover {
   pointer-events: none;
   color: #e1e1e1;
}

Java: Local variable mi defined in an enclosing scope must be final or effectively final

The error means you cannot use the local variable mi inside an inner class.


To use a variable inside an inner class you must declare it final. As long as mi is the counter of the loop and final variables cannot be assigned, you must create a workaround to get mi value in a final variable that can be accessed inside inner class:

final Integer innerMi = new Integer(mi);

So your code will be like this:

for (int mi=0; mi<colors.length; mi++){

    String pos = Character.toUpperCase(colors[mi].charAt(0)) + colors[mi].substring(1);
    JMenuItem Jmi =new JMenuItem(pos);
    Jmi.setIcon(new IconA(colors[mi]));

    // workaround:
    final Integer innerMi = new Integer(mi);

    Jmi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JMenuItem item = (JMenuItem) e.getSource();
                IconA icon = (IconA) item.getIcon();
                // HERE YOU USE THE FINAL innerMi variable and no errors!!!
                Color kolorIkony = getColour(colors[innerMi]); 
                textArea.setForeground(kolorIkony);
            }
        });

        mnForeground.add(Jmi);
    }
}

Convert Decimal to Varchar

I think CAST(ROUND(yourColumn,2) as varchar) should do the job.

But why do you want to do this presentational formatting in T-SQL?

How to delete rows in tables that contain foreign keys to other tables

You can alter a foreign key constraint with delete cascade option as shown below. This will delete chind table rows related to master table rows when deleted.

ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz 
FOREIGN KEY (xyz) 
REFERENCES ChildTable (xyz) ON DELETE CASCADE 

Is it not possible to stringify an Error using JSON.stringify?

You can solve this with a one-liner( errStringified ) in plain javascript:

var error = new Error('simple error message');
var errStringified = (err => JSON.stringify(Object.getOwnPropertyNames(Object.getPrototypeOf(err)).reduce(function(accumulator, currentValue) { return accumulator[currentValue] = err[currentValue], accumulator}, {})))(error);
console.log(errStringified);

It works with DOMExceptions as well.

Getting value from appsettings.json in .net core

.NET core 3.X

no need to create new model and to set in Startup.cs.

Controller Add new package - using Microsoft.Extensions.Configuration;

public class HomeController : Controller
{
    private readonly IConfiguration _mySettings;

    public HomeController (IConfiguration mySettings)
    {
         _mySettings= mySettings;
    }
 
    //ex: you can get value on below function 
    public IEnumerable<string> Get()
    {
        var result = _config.GetValue<string>("AppSettings:Version"); // "One"
        return new string[] { result.ToString() };
    }
}

Checking if a collection is null or empty in Groovy

FYI this kind of code works (you can find it ugly, it is your right :) ) :

def list = null
list.each { println it }
soSomething()

In other words, this code has null/empty checks both useless:

if (members && !members.empty) {
    members.each { doAnotherThing it }
}

def doAnotherThing(def member) {
  // Some work
}

Align text in a table header

For me none of the above worked. I think it is because I have two levels of header and a fixed width on level 1. So I couldn't align the text inside the corresponding columns on level 2.

+---------------------------+
|           lvl 1           |
+---------------------------+
| lvl 2 col a | lvl 2 col b |
+---------------------------+

I had to use the combination of width:auto and text:align-center :

<th style="width:auto;text-align:center">lvl 2 col a</th>
<th style="width:auto;text-align:center">lvl 2 col b</th>

Remove directory from remote repository after adding them to .gitignore

Blundell's first answer didn't work for me. However it showed me the right way. I have done the same thing like this:

> for i in `git ls-files -i --exclude-from=.gitignore`; do git rm --cached $i; done
> git commit -m 'Removed all files that are in the .gitignore'
> git push origin master

I advise you to check the files to be deleted first by running the below statement:

git ls-files -i --exclude-from=.gitignore

I was using a default .gitignore file for visual studio and I noticed that it was removing all log and bin folders in the project which was not my intended action.

Get number of digits with JavaScript

Two digits: simple function in case you need two or more digits of a number with ECMAScript 6 (ES6):

const zeroDigit = num => num.toString().length === 1 ? `0${num}` : num;

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

For Windows, I was able to get it working by enabling TLS for secure communication on the SMTP Virtual server. TLS will not be available on the SMTP virtual server without a certificate. This link will give the steps needed.

https://support.microsoft.com/en-ie/help/4014125/how-to-configure-iis-smtp-for-outgoing-tls-authentication

How to control the line spacing in UILabel

Swift 3 extension:

import UIKit
    
extension UILabel {
  func setTextWithLineSpacing(text: String, lineHeightMultiply: CGFloat = 1.3) {
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineHeightMultiple = lineHeightMultiply
    paragraphStyle.alignment = .center
    let attributedString = NSMutableAttributedString(string: text)
    attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
    self.attributedText = attributedString
  }
}

jQuery 'each' loop with JSON array

Brief code but full-featured

The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.

The jquery each runs the inner loop; I needed the regular JavaScript for on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.

This is only 5 main lines of code but wrapped onto multiple lines for display:

$.get("data.php", function(data){

    for (var propTitle in data) {

        $('<div></div>') 
            .addClass('heading')
            .insertBefore('#contentHere')
            .text(propTitle);

            $(data[propTitle]).each(function(iRec, oRec) {

                $('<div></div>')
                    .addClass(oRec.textType)
                    .attr('id', 'T'+oRec.textId)
                    .insertBefore('#contentHere')
                    .text(oRec.text);
            });
    }

});

Produces the output

(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")

<div class="heading">
    justIn
</div>
<div id="T123" class="Greeting">
    1Hello
</div>
<div id="T514" class="Question">
    1What's up?
</div>
<div id="T122" class="Order">
    1Come over here
</div>
<div class="heading">
    recent
</div>
<div id="T1255" class="Greeting">
    2Hello
</div>
<div id="T6564" class="Question">
    2What's up?
</div>
<div id="T0192" class="Order">
    2Come over here
</div>
<div class="heading">
    old
</div>
<div id="T5213" class="Greeting">
    3Hello
</div>
<div id="T9758" class="Question">
    3What's up?
</div>
<div id="T7655" class="Order">
    3Come over here
</div>
<div id="contentHere"></div>

Apply a style sheet

<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>

to get a "beautiful" looking set of data

alt text

More Info
The JSON data was used in the following way:

for each category (key name the array is held under):

  • the key name is used as the section heading (e.g. justIn)

for each object held inside an array:

  • 'text' becomes the content of a div
  • 'textType' becomes the class of the div (hooked into a style sheet)
  • 'textId' becomes the id of the div
  • e.g. <div id="T122" class="Order">Come over here</div>

AngularJS HTTP post to PHP and undefined

angularjs .post() defaults the Content-type header to application/json. You are overriding this to pass form-encoded data, however you are not changing your data value to pass an appropriate query string, so PHP is not populating $_POST as you expect.

My suggestion would be to just use the default angularjs setting of application/json as header, read the raw input in PHP, and then deserialize the JSON.

That can be achieved in PHP like this:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;

Alternately, if you are heavily relying on $_POST functionality, you can form a query string like [email protected]&password=somepassword and send that as data. Make sure that this query string is URL encoded. If manually built (as opposed to using something like jQuery.serialize()), Javascript's encodeURIComponent() should do the trick for you.

How to show validation message below each textbox using jquery?

This is the simple solution may work for you.

Check this solution

$('form').on('submit', function (e) {
e.preventDefault();
var emailBox=$("#email");
var passBox=$("#password");
if (!emailBox.val() || !passBox.val()) {
    $(".validationText").text("Please Enter Value").show();
}
else if(!IsEmail(emailBox.val()))
{
    emailBox.prev().text("Invalid E-mail").show();
}
$("input#email, input#password").focus(function(){
    $(this).prev(".validationText").hide();
});});

How to define static constant in a class in swift

If you actually want a static property of your class, that isn't currently supported in Swift. The current advice is to get around that by using global constants:

let testStr = "test"
let testStrLen = countElements(testStr)

class MyClass {
    func myFunc() {
    }
}

If you want these to be instance properties instead, you can use a lazy stored property for the length -- it will only get evaluated the first time it is accessed, so you won't be computing it over and over.

class MyClass {
    let testStr: String = "test"
    lazy var testStrLen: Int = countElements(self.testStr)

    func myFunc() {
    }
}

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

height: calc(100%) not working correctly in CSS

try setting both html and body to height 100%;

html, body {background: blue; height:100%;}

WAMP shows error 'MSVCR100.dll' is missing when install

To solve this issue you have to install all Microsoft redistribution packages 2010,2012(x86 and x64) than uninstall wampserver from control panel and reinstall new copy of wamp server this error will be get fixed

Parse JSON with R

Try below code using RJSONIO in console

library(RJSONIO)
library(RCurl)


json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")

json_file2 = RJSONIO::fromJSON(json_file)

head(json_file2)

Animate the transition between fragments

You need to use the new android.animation framework (object animators) with FragmentTransaction.setCustomAnimations as well as FragmentTransaction.setTransition.

Here's an example on using setCustomAnimations from ApiDemos' FragmentHideShow.java:

ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);

and here's the relevant animator XML from res/animator/fade_in.xml:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:interpolator/accelerate_quad"
    android:valueFrom="0"
    android:valueTo="1"
    android:propertyName="alpha"
    android:duration="@android:integer/config_mediumAnimTime" />

Note that you can combine multiple animators using <set>, just as you could with the older animation framework.


EDIT: Since folks are asking about slide-in/slide-out, I'll comment on that here.

Slide-in and slide-out

You can of course animate the translationX, translationY, x, and y properties, but generally slides involve animating content to and from off-screen. As far as I know there aren't any transition properties that use relative values. However, this doesn't prevent you from writing them yourself. Remember that property animations simply require getter and setter methods on the objects you're animating (in this case views), so you can just create your own getXFraction and setXFraction methods on your view subclass, like this:

public class MyFrameLayout extends FrameLayout {
    ...
    public float getXFraction() {
        return getX() / getWidth(); // TODO: guard divide-by-zero
    }

    public void setXFraction(float xFraction) {
        // TODO: cache width
        final int width = getWidth();
        setX((width > 0) ? (xFraction * width) : -9999);
    }
    ...
}

Now you can animate the 'xFraction' property, like this:

res/animator/slide_in.xml:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:valueFrom="-1.0"
    android:valueTo="0"
    android:propertyName="xFraction"
    android:duration="@android:integer/config_mediumAnimTime" />

Note that if the object you're animating in isn't the same width as its parent, things won't look quite right, so you may need to tweak your property implementation to suit your use case.

Handle file download from ajax post

For those looking for a solution from an Angular perspective, this worked for me:

$http.post(
  'url',
  {},
  {responseType: 'arraybuffer'}
).then(function (response) {
  var headers = response.headers();
  var blob = new Blob([response.data],{type:headers['content-type']});
  var link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = "Filename";
  link.click();
});

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

As an improvement to both Praveen and Tony, I use an override:

public partial class MyDatabaseEntities : DbContext
{
    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                        validationErrors.Entry.Entity.GetType().FullName,
                        validationError.PropertyName,
                        validationError.ErrorMessage);
                }
            }

            throw;  // You can also choose to handle the exception here...
        }
    }
}

What is the 'dynamic' type in C# 4.0 used for?

The dynamic keyword is new to C# 4.0, and is used to tell the compiler that a variable's type can change or that it is not known until runtime. Think of it as being able to interact with an Object without having to cast it.

dynamic cust = GetCustomer();
cust.FirstName = "foo"; // works as expected
cust.Process(); // works as expected
cust.MissingMethod(); // No method found!

Notice we did not need to cast nor declare cust as type Customer. Because we declared it dynamic, the runtime takes over and then searches and sets the FirstName property for us. Now, of course, when you are using a dynamic variable, you are giving up compiler type checking. This means the call cust.MissingMethod() will compile and not fail until runtime. The result of this operation is a RuntimeBinderException because MissingMethod is not defined on the Customer class.

The example above shows how dynamic works when calling methods and properties. Another powerful (and potentially dangerous) feature is being able to reuse variables for different types of data. I'm sure the Python, Ruby, and Perl programmers out there can think of a million ways to take advantage of this, but I've been using C# so long that it just feels "wrong" to me.

dynamic foo = 123;
foo = "bar";

OK, so you most likely will not be writing code like the above very often. There may be times, however, when variable reuse can come in handy or clean up a dirty piece of legacy code. One simple case I run into often is constantly having to cast between decimal and double.

decimal foo = GetDecimalValue();
foo = foo / 2.5; // Does not compile
foo = Math.Sqrt(foo); // Does not compile
string bar = foo.ToString("c");

The second line does not compile because 2.5 is typed as a double and line 3 does not compile because Math.Sqrt expects a double. Obviously, all you have to do is cast and/or change your variable type, but there may be situations where dynamic makes sense to use.

dynamic foo = GetDecimalValue(); // still returns a decimal
foo = foo / 2.5; // The runtime takes care of this for us
foo = Math.Sqrt(foo); // Again, the DLR works its magic
string bar = foo.ToString("c");

Read more feature : http://www.codeproject.com/KB/cs/CSharp4Features.aspx

Bash foreach loop

"foreach" is not the name for bash. It is simply "for". You can do things in one line only like:

for fn in `cat filenames.txt`; do cat "$fn"; done

Reference: http://www.cyberciti.biz/faq/linux-unix-bash-for-loop-one-line-command/

Non greedy (reluctant) regex matching in sed?

In this specific case, you can get the job done without using a non-greedy regex.

Try this non-greedy regex [^/]* instead of .*?:

sed 's|\(http://[^/]*/\).*|\1|g'

Compile error: package javax.servlet does not exist

This is what I found. Adding /usr/local/apache-tomcat-7.0.64/lib/servlet-api.jar in my environment variable as CLASSPATH. OS is iOS.

if using bash: ~/.bash_profile $CLASSPATH=/usr/local/apache-tomcat-7.0.64/lib/servlet-api.jar

if using zsh: ~/.zshrc export CLASSPATH="usr/local/apache-tomcat-7.0.64/lib/servlet-api.jar"

Force it work right now, run source .bash_profile (or .zshrc) or one can restart computer and it works for the current user.

No connection could be made because the target machine actively refused it 127.0.0.1

If you have this while Fiddler is running -> in Fiddler, go to 'Rules' and disable 'Automatically Authenticate' and it should work again.

How to truncate a foreign key constrained table?

Getting the old foreign key check state and sql mode are best way to truncate / Drop the table as Mysql Workbench do while synchronizing model to database.

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;`
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

DROP TABLE TABLE_NAME;
TRUNCATE TABLE_NAME;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

Can I multiply strings in Java to repeat sequences?

With Guava:

Joiner.on("").join(Collections.nCopies(i, someNum));

Can I use jQuery to check whether at least one checkbox is checked?

$("#frmTest").submit(function(){
    var checked = $("#frmText input:checked").length > 0;
    if (!checked){
        alert("Please check at least one checkbox");
        return false;
    }
});

converting Java bitmap to byte array

Do you need to rewind the buffer, perhaps?

Also, this might happen if the stride (in bytes) of the bitmap is greater than the row length in pixels * bytes/pixel. Make the length of bytes b.remaining() instead of size.

How to check whether input value is integer or float?

How about this. using the modulo operator

if(a%b==0) 
{
    System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
    System.out.println("b is NOT a factor of a");
}

Proxy setting for R

Inspired by all the responses related on the internet, finally I've found the solution to correctly configure the Proxy for R and Rstudio.

There are several steps to follow, perhaps some of the steps are useless, but the combination works!

  1. Add environment variables http_proxy and https_proxy with proxy details.

    variable name: http_proxy
    variable value: https://user_id:password@your_proxy:your_port/
    
    variable name: https_proxy
    variable value: https:// user_id:password@your_proxy:your_port
    
  2. If you start R from a desktop icon, you can add the --internet flag to the target line (right click -> Properties)

    e.g."C:\Program Files\R\R-2.8.1\bin\Rgui.exe" --internet2

  3. For RStudio just you have to do this:

    Firstly, open RStudio like always, select from the top menu:

    Tools-Global Options-Packages

    Uncheck the option: Use Internet Explorer library/proxy for HTTP

  4. Find the file (.Renviron) in your computer, most probably you would find it here: C:\Users\your user name\Documents.

    Note that: if it does not exist you can create it just by writing this command in R:

    file.edit('~/.Renviron')
    

    Then add these six lines to the initials of the file:

    options(internet.info = 0)
    
    http_proxy = https:// user_id:password@your_proxy:your_port
    
    http_proxy_user = user_id:password
    
    https_proxy = https:// user_id:password0@your_proxy:your_port
    
    https_proxy_user = user_id:password
    
    ftp_proxy = user_id:password@your_proxy:your_port
    
  5. Restart R. Type the following commands in R to assure that the configuration above works well:

    Sys.getenv("http_proxy")
    
    Sys.getenv("http_proxy_user")
    
    Sys.getenv("https_proxy")
    
    Sys.getenv("https_proxy_user")
    
    Sys.getenv("ftp_proxy")
    
  6. Now you can install the packages as you want by using the command like:

    install.packages("mlr",method="libcurl")
    

    It's important to add method="libcurl", otherwise it won't work.

Presenting modal in iOS 13 fullscreen

This worked for me

let vc = self.storyboard?.instantiateViewController(withIdentifier: "storyboardID_cameraview1") as! CameraViewController
  
vc.modalPresentationStyle = .fullScreen
    
self.present(vc, animated: true, completion: nil)`