Programs & Examples On #Grails domain class

deals with issues related to the definitions of domain model

How to write a simple Java program that finds the greatest common divisor between two numbers?

public static int GCD(int x, int y) {   
    int r;
    while (y!=0) {
        r = x%y;
        x = y;
        y = r;
    }
    return x;
}

Get keys of a Typescript interface as array of strings

Instead of defining IMyTable as in interface, try defining it as a class. In typescript you can use a class like an interface.

So for your example, define/generate your class like this:

export class IMyTable {
    constructor(
        public id = '',
        public title = '',
        public createdAt: Date = null,
        public isDeleted = false
    )
}

Use it as an interface:

export class SomeTable implements IMyTable {
    ...
}

Get keys:

const keys = Object.keys(new IMyTable());

How to easily get network path to the file you are working on?

Easiest way to find address path in Excel 2010:

File - info - properties (on right) - (drop-down menu) - advanced properties - general tab

You will get to the same properties box that was so simple to find in Excel 2003.

How to easily resize/optimize an image size with iOS?

The easiest and most straightforward way to resize your images would be this

float actualHeight = image.size.height;
float actualWidth = image.size.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = 320.0/480.0;

if(imgRatio!=maxRatio){
    if(imgRatio < maxRatio){
        imgRatio = 480.0 / actualHeight;
        actualWidth = imgRatio * actualWidth;
        actualHeight = 480.0;
    }
    else{
        imgRatio = 320.0 / actualWidth;
        actualHeight = imgRatio * actualHeight;
        actualWidth = 320.0;
    }
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

Adobe Flash Builder 4.6 Read Me.pdf recommendeds that you edit the eclipse.ini file for your Eclipse instance, so that it includes the following settings:

-vmargs -Xms256m -Xmx512m -XX:MaxPermSize=256m -XX:PermSize=64m

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.

One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).

Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.

-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CallTime DATETIME NOT NULL DEFAULT GETDATE(),
   CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
   Subject VARCHAR(250) NOT NULL,
   Notes VARCHAR(8000) NOT NULL,
   Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
   PhoneCallID INT NOT NULL,
   TicketID INT NOT NULL
)

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

Android Relative Layout Align Center

I hope this will work

EDITED

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingRight="15dp" >

    <ImageView
        android:id="@+id/place_category_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:contentDescription="ss"
        android:paddingTop="10dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/place_distance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="320" />

    <TextView
        android:id="@+id/place_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@+id/place_category_icon"
        android:text="Place Name"
        android:textColor="#FFFF00"
        android:textSize="14sp"
        android:textStyle="bold" />

</RelativeLayout>

Why is "npm install" really slow?

One thing I noticed is, if you are working in new project(folder) you have to reconfigure proxy setting for the particular path

  1. Cd(change terminal window path to the destination folder.

  2. npm config set proxy http://(ip address):(port)

  3. npm config set https-proxy http://(ip address):(port)

  4. npm install -g @angular/cli

How to get a float result by dividing two integer values using T-SQL?

It's not necessary to cast both of them. Result datatype for a division is always the one with the higher data type precedence. Thus the solution must be:

SELECT CAST(1 AS float) / 3

or

SELECT 1 / CAST(3 AS float)

ASP MVC href to a controller/view

how about

<li>
<a href="@Url.Action("Index", "Users")" class="elements"><span>Clients</span></a>
</li>

Ajax Success and Error function failure

This may be an old post but I realized there is nothing to be returned from the php and your success function does not have input like as follows, success:function(e){}. I hope that helps you.

How can I hash a password in Java?

While the NIST recommendation PBKDF2 has already been mentioned, I'd like to point out that there was a public password hashing competition that ran from 2013 to 2015. In the end, Argon2 was chosen as the recommended password hashing function.

There is a fairly well adopted Java binding for the original (native C) library that you can use.

In the average use-case, I don't think it does matter from a security perspective if you choose PBKDF2 over Argon2 or vice-versa. If you have strong security requirements, I recommend considering Argon2 in your evaluation.

For further information on the security of password hashing functions see security.se.

Vertically align an image inside a div with responsive height

Make another div and add both 'dummy' and 'img-container' inside the div

Do HTML and CSS like follows

_x000D_
_x000D_
html , body {height:100%;}_x000D_
.responsive-container { height:100%; display:table; text-align:center; width:100%;}_x000D_
.inner-container {display:table-cell; vertical-align:middle;}
_x000D_
<div class="responsive-container">_x000D_
    <div class="inner-container">_x000D_
  <div class="dummy">Sample</div>_x000D_
  <div class="img-container">_x000D_
   Image tag_x000D_
  </div>_x000D_
 </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Instead of 100% for the 'responsive-container' you can give the height that you want.,

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

If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.

moment(endDate).diff(moment(beginDate), 'days');

Additional details can be found in the moment.js page

Cheers, Miguel

EF Code First "Invalid column name 'Discriminator'" but no inheritance

Here is the Fluent API syntax.

http://blogs.msdn.com/b/adonet/archive/2010/12/06/ef-feature-ctp5-fluent-api-samples.aspx

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { 
        get {
            return this.FirstName + " " + this.LastName;
        }
    }
}

class PersonViewModel : Person
{
    public bool UpdateProfile { get; set; }
}


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // ignore a type that is not mapped to a database table
    modelBuilder.Ignore<PersonViewModel>();

    // ignore a property that is not mapped to a database column
    modelBuilder.Entity<Person>()
        .Ignore(p => p.FullName);

}

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."; 


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

How can I access iframe elements with Javascript?

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src.

Convert an enum to List<string>

I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

  public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes
}

In a helper class (HelperMethods) I created the following method:

 public static List<string> GetListOfDescription<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
    }

When you call this helper you will get the list of item descriptions.

 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

 public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();
        */

    }

How to debug Spring Boot application with Eclipse?

There's section 19.2 in Spring Boot Reference that tells you about starting your application with remote debugging support enabled.

$ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
   -jar target/myproject-0.0.1-SNAPSHOT.jar

After you start your application just add that Remote Java Application configuration in Run/Debug configurations, select the port/address you defined when starting your app, and then you are free to debug.

Python "\n" tag extra line

Add , after the print "\n" line

so that it reads print "\n",

How to export the Html Tables data into PDF using Jspdf

Here is an example I think that will help you

<!DOCTYPE html>
<html>
<head>
<script src="js/min.js"></script>
<script src="js/pdf.js"></script>
<script>
    $(function(){
         var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

   $('#cmd').click(function () {

        var table = tableToJson($('#StudentInfoListTable').get(0))
        var doc = new jsPDF('p','pt', 'a4', true);
        doc.cellInitialize();
        $.each(table, function (i, row){
            console.debug(row);
            $.each(row, function (j, cell){
                doc.cell(10, 50,120, 50, cell, i);  // 2nd parameter=top margin,1st=left margin 3rd=row cell width 4th=Row height
            })
        })


        doc.save('sample-file.pdf');
    });
    function tableToJson(table) {
    var data = [];

    // first row needs to be headers
    var headers = [];
    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }


    // go through cells
    for (var i=0; i<table.rows.length; i++) {

        var tableRow = table.rows[i];
        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {

            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

        }

        data.push(rowData);
    }       

    return data;
}
});
</script>
</head>
<body>
<div id="table">
<table id="StudentInfoListTable">
                <thead>
                    <tr>    
                        <th>Name</th>
                        <th>Email</th>
                        <th>Track</th>
                        <th>S.S.C Roll</th>
                        <th>S.S.C Division</th>
                        <th>H.S.C Roll</th>
                        <th>H.S.C Division</th>
                        <th>District</th>

                    </tr>
                </thead>
                <tbody>

                        <tr>
                            <td>alimon  </td>
                            <td>Email</td>
                            <td>1</td>
                            <td>2222</td>
                            <td>as</td>
                            <td>3333</td>
                            <td>dd</td>
                            <td>33</td>
                        </tr>               
                </tbody>
            </table>
<button id="cmd">Submit</button>
</body>
</html>

Here the output

enter image description here

How to make a transparent border using CSS?

Using the :before pseudo-element,
CSS3's border-radius,
and some transparency is quite easy:

LIVE DEMO

enter image description here

<div class="circle"></div>

CSS:

.circle, .circle:before{
  position:absolute;
  border-radius:150px;  
}
.circle{  
  width:200px;
  height:200px;
  z-index:0;
  margin:11%;
  padding:40px;
  background: hsla(0, 100%, 100%, 0.6);   
}
.circle:before{
  content:'';
  display:block;
  z-index:-1;  
  width:200px;
  height:200px;

  padding:44px;
  border: 6px solid hsla(0, 100%, 100%, 0.6);
  /* 4px more padding + 6px border = 10 so... */  
  top:-10px;
  left:-10px; 
}

The :before attaches to our .circle another element which you only need to make (ok, block, absolute, etc...) transparent and play with the border opacity.

Use dynamic variable names in JavaScript

This is an example :

for(var i=0; i<=3; i++) {
    window['p'+i] = "hello " + i;
}

alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3

Another example :

var myVariable = 'coco';
window[myVariable] = 'riko';

alert(coco); // display : riko

So, the value "coco" of myVariable becomes a variable coco.

Because all the variables in the global scope are properties of the Window object.

Don't change link color when a link is clicked

Don't over complicate it. Just give the link a color using the tags. It will leave a constant color that won't change even if you click it. So in your case just set it to blue. If it is set to a particular color of blue just you want to copy, you can press "print scrn" on your keyboard, paste in paint, and using the color picker(shaped as a dropper) pick the color of the link and view the code in the color settings.

slideToggle JQuery right to left

I know it's been a year since this was asked, but just for people that are going to visit this page I am posting my solution.

By using what @Aldi Unanto suggested here is a more complete answer:

  jQuery('.show_hide').click(function(e) {
    e.preventDefault();
    if (jQuery('.slidingDiv').is(":visible") ) {
      jQuery('.slidingDiv').stop(true,true).hide("slide", { direction: "left" }, 200);
    } else {
      jQuery('.slidingDiv').stop(true,true).show("slide", { direction: "left" }, 200);
    }
  });

First I prevent the link from doing anything on click. Then I add a check if the element is visible or not. When visible I hide it. When hidden I show it. You can change direction to left or right and duration from 200 ms to anything you like.

Edit: I have also added

.stop(true,true)

in order to clearQueue and jumpToEnd. Read about jQuery stop here

How to redirect user's browser URL to a different page in Nodejs?

response.writeHead(301,
  {Location: 'http://whateverhostthiswillbe:8675/'+newRoom}
);
response.end();

Is there a common Java utility to break a list into batches?

Using various cheats from the web, I came to this solution:

int[] count = new int[1];
final int CHUNK_SIZE = 500;
Map<Integer, List<Long>> chunkedUsers = users.stream().collect( Collectors.groupingBy( 
    user -> {
        count[0]++;
        return Math.floorDiv( count[0], CHUNK_SIZE );
    } )
);

We use count to mimic a normal collection index.
Then, we group the collection elements in buckets, using the algebraic quotient as bucket number.
The final map contains as key the bucket number, as value the bucket itself.

You can then easily do an operation on each of the buckets with:

chunkedUsers.values().forEach( ... );

How can I use UIColorFromRGB in Swift?

Here's a Swift version of that function (for getting a UIColor representation of a UInt value):

func UIColorFromRGB(rgbValue: UInt) -> UIColor {
    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}

view.backgroundColor = UIColorFromRGB(0x209624)

how to add the missing RANDR extension

First off, Xvfb doesn't read configuration from xorg.conf. Xvfb is a variant of the KDrive X servers and like all members of that family gets its configuration from the command line.

It is true that XRandR and Xinerama are mutually exclusive, but in the case of Xvfb there's no Xinerama in the first place. You can enable the XRandR extension by starting Xvfb using at least the following command line options

Xvfb +extension RANDR [further options]

What are advantages of Artificial Neural Networks over Support Vector Machines?

One answer I'm missing here: Multi-layer perceptron is able to find relation between features. For example it is necessary in computer vision when a raw image is provided to the learning algorithm and now Sophisticated features are calculated. Essentially the intermediate levels can calculate new unknown features.

Reading a string with scanf

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

Which are more performant, CTE or temporary tables?

One use where I found CTE's excelled performance wise was where I needed to join a relatively complex Query on to a few tables which had a few million rows each.

I used the CTE to first select the subset based of the indexed columns to first cut these tables down to a few thousand relevant rows each and then joined the CTE to my main query. This exponentially reduced the runtime of my query.

Whilst results for the CTE are not cached and table variables might have been a better choice I really just wanted to try them out and found the fit the above scenario.

How to download and save a file from Internet using Java?

There are many elegant and efficient answers here. But the conciseness can make us lose some useful information. In particular, one often does not want to consider a connection error an Exception, and one might want to treat differently some kind of network-related errors - for example, to decide if we should retry the download.

Here's a method that does not throw Exceptions for network errors (only for truly exceptional problems, as malformed url or problems writing to the file)

/**
 * Downloads from a (http/https) URL and saves to a file. 
 * Does not consider a connection error an Exception. Instead it returns:
 *  
 *    0=ok  
 *    1=connection interrupted, timeout (but something was read)
 *    2=not found (FileNotFoundException) (404) 
 *    3=server error (500...) 
 *    4=could not connect: connection timeout (no internet?) java.net.SocketTimeoutException
 *    5=could not connect: (server down?) java.net.ConnectException
 *    6=could not resolve host (bad host, or no internet - no dns)
 * 
 * @param file File to write. Parent directory will be created if necessary
 * @param url  http/https url to connect
 * @param secsConnectTimeout Seconds to wait for connection establishment
 * @param secsReadTimeout Read timeout in seconds - trasmission will abort if it freezes more than this 
 * @return See above
 * @throws IOException Only if URL is malformed or if could not create the file
 */
public static int saveUrl(final Path file, final URL url, 
  int secsConnectTimeout, int secsReadTimeout) throws IOException {
    Files.createDirectories(file.getParent()); // make sure parent dir exists , this can throw exception
    URLConnection conn = url.openConnection(); // can throw exception if bad url
    if( secsConnectTimeout > 0 ) conn.setConnectTimeout(secsConnectTimeout * 1000);
    if( secsReadTimeout > 0 ) conn.setReadTimeout(secsReadTimeout * 1000);
    int ret = 0;
    boolean somethingRead = false;
    try (InputStream is = conn.getInputStream()) {
        try (BufferedInputStream in = new BufferedInputStream(is); OutputStream fout = Files
                .newOutputStream(file)) {
            final byte data[] = new byte[8192];
            int count;
            while((count = in.read(data)) > 0) {
                somethingRead = true;
                fout.write(data, 0, count);
            }
        }
    } catch(java.io.IOException e) { 
        int httpcode = 999;
        try {
            httpcode = ((HttpURLConnection) conn).getResponseCode();
        } catch(Exception ee) {}
        if( somethingRead && e instanceof java.net.SocketTimeoutException ) ret = 1;
        else if( e instanceof FileNotFoundException && httpcode >= 400 && httpcode < 500 ) ret = 2; 
        else if( httpcode >= 400 && httpcode < 600 ) ret = 3; 
        else if( e instanceof java.net.SocketTimeoutException ) ret = 4; 
        else if( e instanceof java.net.ConnectException ) ret = 5; 
        else if( e instanceof java.net.UnknownHostException ) ret = 6;  
        else throw e;
    }
    return ret;
}

Remove innerHTML from div

To remove all child elements from your div:

$('#mysweetdiv').empty();

.removeData() and the corresponding .data() function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:

var $li = $('<li>Joe</li>').data('id', 25);

Where is my m2 folder on Mac OS X Mavericks

It's in your home folder but it's hidden by default.

Typing the below commands in the terminal made it visible for me (only the .m2 folder that is, not all the other hidden folders).

> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2         

Source

How to store the hostname in a variable in a .bat file?

 set host=%COMPUTERNAME%
 echo %host%

This one enough. no need of extra loops of big coding.

Flushing footer to bottom of the page, twitter bootstrap

HTML

<div id="wrapper">

  <div id="content">
    <!-- navbar and containers here -->
  </div>

  <div id="footer">
   <!-- your footer here -->
  </div>

</div>

CSS

html, body {
  height: 100%;
}

#wrapper {
  min-height: 100%;
  position: relative;
}

#content {
  padding-bottom: 100px; /* Height of the footer element */
}

#footer {
  width: 100%;
  height: 100px; /* Adjust to the footer needs */
  position: absolute;
  bottom: 0;
  left: 0;
}

How to make tesseract to recognize only numbers, when they are mixed with letters?

For tesseract 3, i try to create config file according FAQ.

BEFORE calling an Init function or put this in a text file called tessdata/configs/digits:

tessedit_char_whitelist 0123456789                 

then, it works by using the command: tesseract imagename outputbase digits

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

There is a special security expression in spring security:

hasAnyRole(list of roles) - true if the user has been granted any of the roles specified (given as a comma-separated list of strings).

I have never used it but I think it is exactly what you are looking for.

Example usage:

<security:authorize access="hasAnyRole('ADMIN', 'DEVELOPER')">
    ...
</security:authorize>

Here is a link to the reference documentation where the standard spring security expressions are described. Also, here is a discussion where I described how to create custom expression if you need it.

Convert from List into IEnumerable format

You don't need to convert it. List<T> implements the IEnumerable<T> interface so it is already an enumerable.

This means that it is perfectly fine to have the following:

public IEnumerable<Book> GetBooks()
{
    List<Book> books = FetchEmFromSomewhere();    
    return books;
}

as well as:

public void ProcessBooks(IEnumerable<Book> books)
{
    // do something with those books
}

which could be invoked:

List<Book> books = FetchEmFromSomewhere();    
ProcessBooks(books);

'was not declared in this scope' error

Here's a simplified example based on of your problem:

if (test) 
{//begin scope 1
    int y = 1; 
}//end scope 1
else 
{//begin scope 2
    int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope

In the above version you have a variable called y that is confined to scope 1, and another different variable called y that is confined to scope 2. You then try to refer to a variable named y after the end of the if, and not such variable y can be seen because no such variable exists in that scope.

You solve the problem by placing y in the outermost scope which contains all references to it:

int y;
if (test) 
{
    y = 1; 
}
else 
{
    y = 2;
}
int x = y;

I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.

Javascript set img src

Your src property is an object because you are setting the src element to be the entire image you created in JavaScript.

Try

document["pic1"].src = searchPic.src;

Broadcast receiver for checking internet connection in android app

Answer to your first question: Your broadcast receiver is being called two times because

You have added two <intent-filter>

  1. Change in network connection :
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

  2. Change in WiFi state:
    <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />

Just use one:
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />.

It will respond to only one action instead of two. See here for more information.

Answer to your second question (you want receiver to call only one time if internet connection available):

Your code is perfect; you notify only when internet is available.

UPDATE

You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.

public boolean isOnline(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    //should check null because in airplane mode it will be null
    return (netInfo != null && netInfo.isConnected());
}

Reverse each individual word of "Hello World" string with Java

Heres a method that takes a string and reverses it.

public String reverse ( String s ) {
            int length = s.length(), last = length - 1;
            char[] chars = s.toCharArray();
            for ( int i = 0; i < length/2; i++ ) {
                char c = chars[i];
                chars[i] = chars[last - i];
                chars[last - i] = c;
            }
            return new String(chars);
        }

First you need to split the string into words like this

String sample = "hello world";  
String[] words = sample.split(" ");  

How to get the hostname of the docker host from inside a docker container on that host without env vars

I know it's an old question, but I needed this solution too, and I acme with another solution.

I used an entrypoint.sh to execute the following line, and define a variable with the actual hostname for that instance:

HOST=`hostname --fqdn`

Then, I used it across my entrypoint script:

echo "Value: $HOST"

Hope this helps

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

Cannot run emulator in Android Studio

  • Open Android studio.
  • Go to setting > System Setting > Android SDK
  • Get the "Android SDK Location".
  • Set the environment variable ANDROID_SDK_ROOT to this value.

It worked for me and I'm on Windows 10 and Android studio 2.3.3

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

Remove old Fragment from fragment manager

Probably you instance old fragment it is keeping a reference. See this interesting article Memory leaks in Android — identify, treat and avoid

If you use addToBackStack, this keeps a reference to instance fragment avoiding to Garbage Collector erase the instance. The instance remains in fragments list in fragment manager. You can see the list by

ArrayList<Fragment> fragmentList = fragmentManager.getFragments();

The next code is not the best solution (because don´t remove the old fragment instance in order to avoid memory leaks) but removes the old fragment from fragmentManger fragment list

int index = fragmentManager.getFragments().indexOf(oldFragment);
fragmentManager.getFragments().set(index, null);

You cannot remove the entry in the arrayList because apparenly FragmentManager works with index ArrayList to get fragment.

I usually use this code for working with fragmentManager

public void replaceFragment(Fragment fragment, Bundle bundle) {

    if (bundle != null)
        fragment.setArguments(bundle);

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());

    //if oldFragment already exits in fragmentManager use it
    if (oldFragment != null) {
        fragment = oldFragment;
    }

    fragmentTransaction.replace(R.id.frame_content_main, fragment, fragment.getClass().getName());

    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

    fragmentTransaction.commit();
}

C# - Create SQL Server table programmatically

For managing DataBase Objects in SQL Server i would suggest using Server Management Objects

Preserve Line Breaks From TextArea When Writing To MySQL

Here is what I use

$textToStore = nl2br(htmlentities($inputText, ENT_QUOTES, 'UTF-8'));

$inputText is the text provided by either the form or textarea. $textToStore is the returned text from nl2br and htmlentities, to be stored in your database. ENT_QUOTES will convert both double and single quotes, so you'll have no trouble with those.

How do I remove a CLOSE_WAIT socket connection

It is also worth noting that if your program spawns a new process, that process may inherit all your opened handles. Even after your own program closs, those inherited handles can still be alive via the orphaned child process. And they don't necessarily show up quite the same in netstat. But all the same, the socket will hang around in CLOSE_WAIT while this child process is alive.

I had a case where I was running ADB. ADB itself spawns a server process if its not already running. This inherited all my handles initially, but did not show up as owning any of them when I was investigating (the same was true for both macOS and Windows - not sure about Linux).

MySQL: Grant **all** privileges on database

 1. Create the database

CREATE DATABASE db_name;

 2. Create the username for the database db_name

GRANT ALL PRIVILEGES ON db_name.* TO 'username'@'localhost' IDENTIFIED BY 'password';

 3. Use the database

USE db_name;

 4. Finally you are in database db_name and then execute the commands like create , select and insert operations.

"Couldn't read dependencies" error with npm

I ran into this problem after I cloned a git repository to a directory, renamed the directory, then tried to run npm install. I'm not sure what the problem was, but something was bungled. Deleting everything, re-cloning (this time with the correct directory name), and then running npm install resolved my issue.

PHP, get file name without file extension

You can write this

$filename = current(explode(".", $file));

These will return current element of array, if not used before.

How to delete a file or folder?

Here is a robust function that uses both os.remove and shutil.rmtree:

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path) or os.path.islink(path):
        os.remove(path)  # remove the file
    elif os.path.isdir(path):
        shutil.rmtree(path)  # remove dir and all contains
    else:
        raise ValueError("file {} is not a file or dir.".format(path))

Appending a list or series to a pandas DataFrame as a row?

If you want to add a Series and use the Series' index as columns of the DataFrame, you only need to append the Series between brackets:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame()

In [3]: row=pd.Series([1,2,3],["A","B","C"])

In [4]: row
Out[4]: 
A    1
B    2
C    3
dtype: int64

In [5]: df.append([row],ignore_index=True)
Out[5]: 
   A  B  C
0  1  2  3

[1 rows x 3 columns]

Whitout the ignore_index=True you don't get proper index.

How to prevent Right Click option using jquery

If you're looking into trying to disable the downloading/saving of your images, scripts won't stop that. You would probably have better luck doing this on a server configuration level (like modifying your .htaccess for example on Apache).

Try asking this on ServerFault.

Python: call a function from string name

You can use a dictionary too.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

Current time formatting with Javascript

function formatTime(date){

  d = new Date(date);
  var h=d.getHours(),m=d.getMinutes(),l="AM";
  if(h > 12){
    h = h - 12;
  }
  if(h < 10){
    h = '0'+h;
  }
  if(m < 10){
    m = '0'+m;
  }
  if(d.getHours() >= 12){
    l="PM"
  }else{
    l="AM"
  }

  return h+':'+m+' '+l;

}

Usage & result:

var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"

Hibernate Union alternatives

Use VIEW. The same classes can be mapped to different tables/views using entity name, so you won't even have much of a duplication. Being there, done that, works OK.

Plain JDBC has another hidden problem: it's unaware of Hibernate session cache, so if something got cached till the end of the transaction and not flushed from Hibernate session, JDBC query won't find it. Could be very puzzling sometimes.

Converting map to struct

Hashicorp's https://github.com/mitchellh/mapstructure library does this out of the box:

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

The second result parameter has to be an address of the struct.

Convert a list to a dictionary in Python

You can also try this approach save the keys and values in different list and then use dict method

data=['test1', '1', 'test2', '2', 'test3', '3', 'test4', '4']

keys=[]
values=[]
for i,j in enumerate(data):
    if i%2==0:
        keys.append(j)
    else:
        values.append(j)

print(dict(zip(keys,values)))

output:

{'test3': '3', 'test1': '1', 'test2': '2', 'test4': '4'}

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

How do I parse an ISO 8601-formatted date?

Several answers here suggest using datetime.datetime.strptime to parse RFC 3339 or ISO 8601 datetimes with timezones, like the one exhibited in the question:

2008-09-03T20:56:35.450686Z

This is a bad idea.

Assuming that you want to support the full RFC 3339 format, including support for UTC offsets other than zero, then the code these answers suggest does not work. Indeed, it cannot work, because parsing RFC 3339 syntax using strptime is impossible. The format strings used by Python's datetime module are incapable of describing RFC 3339 syntax.

The problem is UTC offsets. The RFC 3339 Internet Date/Time Format requires that every date-time includes a UTC offset, and that those offsets can either be Z (short for "Zulu time") or in +HH:MM or -HH:MM format, like +05:00 or -10:30.

Consequently, these are all valid RFC 3339 datetimes:

  • 2008-09-03T20:56:35.450686Z
  • 2008-09-03T20:56:35.450686+05:00
  • 2008-09-03T20:56:35.450686-10:30

Alas, the format strings used by strptime and strftime have no directive that corresponds to UTC offsets in RFC 3339 format. A complete list of the directives they support can be found at https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior, and the only UTC offset directive included in the list is %z:

%z

UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).

Example: (empty), +0000, -0400, +1030

This doesn't match the format of an RFC 3339 offset, and indeed if we try to use %z in the format string and parse an RFC 3339 date, we'll fail:

>>> from datetime import datetime
>>> datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
>>> datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

(Actually, the above is just what you'll see in Python 3. In Python 2 we'll fail for an even simpler reason, which is that strptime does not implement the %z directive at all in Python 2.)

The multiple answers here that recommend strptime all work around this by including a literal Z in their format string, which matches the Z from the question asker's example datetime string (and discards it, producing a datetime object without a timezone):

>>> datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)

Since this discards timezone information that was included in the original datetime string, it's questionable whether we should regard even this result as correct. But more importantly, because this approach involves hard-coding a particular UTC offset into the format string, it will choke the moment it tries to parse any RFC 3339 datetime with a different UTC offset:

>>> datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%fZ")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

Unless you're certain that you only need to support RFC 3339 datetimes in Zulu time, and not ones with other timezone offsets, don't use strptime. Use one of the many other approaches described in answers here instead.

Why doesn't java.io.File have a close method?

Say suppose, you have

File f  = new File("SomeFile");
f.length();

You need not close the Files, because its just the representation of a path.

You should always consider to close only reader/writers and in fact streams.

How to set JAVA_HOME in Mac permanently?

To set your Java path on mac:

  1. Open terminal on mac, change path to the root cd ~
  2. vi .bash_profile (This opens the bash_profile file)
  3. Click I to insert text and use the following text to set JAVA_HOME and PATH

    • export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home'
    • export PATH=$JAVA_HOME/bin:$PATH

      1. Type :wq to save and exit the file.
      2. Type source .bash_profile to execute the .bash_profile file.
      3. You can type echo $JAVA_HOME or echo $PATH

How do I include a Perl module that's in a different directory?

Most likely the reason your push did not work is order of execution.

use is a compile time directive. You push is done at execution time:

push ( @INC,"directory_path/more_path");
use Foo.pm;  # In directory path/more_path

You can use a BEGIN block to get around this problem:

BEGIN {
    push ( @INC,"directory_path/more_path");
}
use Foo.pm;  # In directory path/more_path

IMO, it's clearest, and therefore best to use lib:

use lib "directory_path/more_path";
use Foo.pm;  # In directory path/more_path

See perlmod for information about BEGIN and other special blocks and when they execute.

Edit

For loading code relative to your script/library, I strongly endorse File::FindLib

You can say use File::FindLib 'my/test/libs'; to look for a library directory anywhere above your script in the path.

Say your work is structured like this:

   /home/me/projects/
    |- shared/
    |   |- bin/
    |   `- lib/
    `- ossum-thing/
       `- scripts 
           |- bin/
           `- lib/

Inside a script in ossum-thing/scripts/bin:

use File::FindLib 'lib/';
use File::FindLib 'shared/lib/';

Will find your library directories and add them to your @INC.

It's also useful to create a module that contains all the environment set-up needed to run your suite of tools and just load it in all the executables in your project.

use File::FindLib 'lib/MyEnvironment.pm'

How to add an image to an svg container using D3.js

I do not know why, but the image should not be duplicated, tripled, etc ... should remove the previous one and load it again but with another rotation data. This is my code:

data.csv enter image description here

d3.csv("data/data.csv").then(function(data){
//console.log(data);
// Clean data
formattedData = data.map(function(id){
id.rot_1 = +id.rot_1;
        id.trans_1 = +id.trans_1;
        return id;
});
// First run of the visualization
update(formattedData[0]);})

$("#play-button")
.on("click", function(){
    var button = $(this);
    if (button.text() == "Play"){
        button.text("Pause");
        interval = setInterval(step, 1000);            
    }
    else {
        button.text("Play");
        clearInterval(interval);
    }})

function step(){
// At the end of our data, loop back
time = (time < 76) ? time+1 : 0
update(formattedData[time]); }

function update(data) {
// Standard transition time for the visualization
var t = d3.transition()
    .duration(1000);

//console.log(d3.selectAll(data));    
//console.log(data)

// original
var imgs1 = g.append("image") // en vez de g es svg
.attr("xlink:href", "img/picturetest.png");

// EXIT old elements not present in new data.
imgs1.exit()
    .attr("class", "exit")
    .selectAll("svg:image")
    .remove();

//console.log(data)

// ENTER new elements present in new data.
imgs1.enter()
    .append("svg:image") // svg:image
    //.attr("xlink:href", "img/picturetest.png")
    .attr("class", "enter")
    .merge(imgs1)
    .transition(t)
        .attr("x", 0) // 150
        .attr("y", 0) // 80
        .attr("width", 200)
        .attr("height", 200)
        .attr("transform", "rotate("+data.rot_1+") translate("+data.trans_1+")" ); }`

What is the difference between :focus and :active?

Using "focus" will give keyboard users the same effect that mouse users get when they hover with a mouse. "Active" is needed to get the same effect in Internet Explorer.

The reality is, these states do not work as they should for all users. Not using all three selectors creates accessibility issues for many keyboard-only users who are physically unable to use a mouse. I invite you to take the #nomouse challenge (nomouse dot org).

How to resize Image in Android?

public Bitmap resizeBitmap(String photoPath, int targetW, int targetH) {
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(photoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    int scaleFactor = 1;
    if ((targetW > 0) || (targetH > 0)) {
            scaleFactor = Math.min(photoW/targetW, photoH/targetH);        
    }

    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true; //Deprecated API 21

    return BitmapFactory.decodeFile(photoPath, bmOptions);            
}

How to Add Incremental Numbers to a New Column Using Pandas

Here:

df = df.reset_index()
df.columns[0] = 'New_ID'
df['New_ID'] = df.index + 880

What is Turing Complete?

From wikipedia:

Turing completeness, named after Alan Turing, is significant in that every plausible design for a computing device so far advanced can be emulated by a universal Turing machine — an observation that has become known as the Church-Turing thesis. Thus, a machine that can act as a universal Turing machine can, in principle, perform any calculation that any other programmable computer is capable of. However, this has nothing to do with the effort required to write a program for the machine, the time it may take for the machine to perform the calculation, or any abilities the machine may possess that are unrelated to computation.

While truly Turing-complete machines are very likely physically impossible, as they require unlimited storage, Turing completeness is often loosely attributed to physical machines or programming languages that would be universal if they had unlimited storage. All modern computers are Turing-complete in this sense.

I don't know how you can be more non-technical than that except by saying "turing complete means 'able to answer computable problem given enough time and space'".

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

what is <meta charset="utf-8">?

The characters you are reading on your screen now each have a numerical value. In the ASCII format, for example, the letter 'A' is 65, 'B' is 66, and so on. If you look at a table of characters available in ASCII you will see that it isn't much use for someone who wishes to write something in Mandarin, Arabic, or Japanese. For characters / words from those languages to be displayed we needed another system of encoding them to and from numbers stored in computer memory.

UTF-8 is just one of the encoding methods that were invented to implement this requirement. It lets you write text in all kinds of languages, so French accents will appear perfectly fine, as will text like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

If you copy and paste the above text into notepad and then try to save the file as ANSI (another format) you will receive a warning that saving in this format will lose some of the formatting. Accept it, then re-load the text file and you'll see something like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

Using "-Filter" with a variable

You don't need quotes around the variable, so simply change this:

Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"}

into this:

Get-ADComputer -Filter {name -like $nameregex -and Enabled -eq "true"}

Note, however, that the scriptblock notation for filter statements is misleading, because the statement is actually a string, so it's better to write it as such:

Get-ADComputer -Filter "name -like '$nameregex' -and Enabled -eq 'true'"

Related. Also related.

And FTR: you're using wildcard matching here (operator -like), not regular expressions (operator -match).

How does Java resolve a relative path in new File()?

The working directory is a common concept across virtually all operating systems and program languages etc. It's the directory in which your program is running. This is usually (but not always, there are ways to change it) the directory the application is in.

Relative paths are ones that start without a drive specifier. So in linux they don't start with a /, in windows they don't start with a C:\, etc. These always start from your working directory.

Absolute paths are the ones that start with a drive (or machine for network paths) specifier. They always go from the start of that drive.

How to horizontally center a floating element of a variable width?

for 50% element

width: 50%;
display: block;
float: right;
margin-right: 25%;

DTO pattern: Best way to copy properties between two objects

I suggest you should use one of the mappers' libraries: Mapstruct, ModelMapper, etc. With Mapstruct your mapper will look like:

@Mapper
public interface UserMapper {     
    UserMapper INSTANCE = Mappers.getMapper( UserMapper.class ); 

    UserDTO toDto(User user);
}

The real object with all getters and setters will be automatically generated from this interface. You can use it like:

UserDTO userDTO = UserMapper.INSTANCE.toDto(user);

You can also add some logic for your activeText filed using @AfterMapping annotation.

Disable automatic sorting on the first column when using jQuery DataTables

Use this simple code for DataTables custom sorting. Its 100% work

<script>
    $(document).ready(function() {
        $('#myTable').DataTable( {
            "order": [[ 0, "desc" ]] // "0" means First column and "desc" is order type; 
        } );
    } );
</script>


See in Datatables website

https://datatables.net/examples/basic_init/table_sorting.html

Find and Replace string in all files recursive using grep and sed

grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"

Repeat each row of data.frame the number of times specified in a column

In case you have to do this operation on very large data.frames I would recommend converting it into a data.table and use the following, which should run much faster:

library(data.table)
dt <- data.table(df)
dt.expanded <- dt[ ,list(freq=rep(1,freq)),by=c("var1","var2")]
dt.expanded[ ,freq := NULL]
dt.expanded

See how much faster this solution is:

df <- data.frame(var1=1:2e3, var2=1:2e3, freq=1:2e3)
system.time(df.exp <- df[rep(row.names(df), df$freq), 1:2])
##    user  system elapsed 
##    4.57    0.00    4.56
dt <- data.table(df)
system.time(dt.expanded <- dt[ ,list(freq=rep(1,freq)),by=c("var1","var2")])
##    user  system elapsed 
##    0.05    0.01    0.06

Way to insert text having ' (apostrophe) into a SQL table

yes, sql server doesn't allow to insert single quote in table field due to the sql injection attack. so we must replace single appostrophe by double while saving.

(he doesn't work for me) must be => (he doesn''t work for me)

Chmod 777 to a folder and all contents

You can give permission to folder and all its contents using option -R i.e Recursive permissions.

But I would suggest not to give 777 permission to all folder and it's all contents. You should give specific permission to each sub-folder in www directory folders.

Ideally, give 755 permission for security reasons to the web folder.

sudo chmod -R 755 /www/store

Each number has meaning in permission. Do not give full permission.

N   Description                      ls   binary    
0   No permissions at all            ---  000
1   Only execute                     --x  001
2   Only write                       -w-  010
3   Write and execute                -wx  011
4   Only read                        r--  100
5   Read and execute                 r-x  101
6   Read and write                   rw-  110
7   Read, write, and execute         rwx  111
  • First Number 7 - Read, write, and execute for the user.
  • Second Number 5 - Read and execute for the group.
  • Third Number 5 - Read and execute for others.

If your production web folder has multiple users, then you can set permissions and user groups accordingly.

More info :

  1. Understanding File Permissions: What Does “Chmod 777" Mean?
  2. What file permissions should I set on web root?
  3. Why shouldn't /var/www have chmod 777

Plot inline or a separate window using Matplotlib in Spyder IDE

Magic commands such as

%matplotlib qt  

work in the iPython console and Notebook, but do not work within a script.

In that case, after importing:

from IPython import get_ipython

use:

get_ipython().run_line_magic('matplotlib', 'inline')

for inline plotting of the following code, and

get_ipython().run_line_magic('matplotlib', 'qt')

for plotting in an external window.

Edit: solution above does not always work, depending on your OS/Spyder version Anaconda issue on GitHub. Setting the Graphics Backend to Automatic (as indicated in another answer: Tools >> Preferences >> IPython console >> Graphics --> Automatic) solves the problem for me.

Then, after a Console restart, one can switch between Inline and External plot windows using the get_ipython() command, without having to restart the console.

What is the difference between MVC and MVVM?

MVVM is a refinement (debatable) of the Presentation Model pattern. I say debatable, because the only difference is in how WPF provides the ability to do data binding and command handling.

Search File And Find Exact Match And Print Line?

you should use regular expressions to find all you need:

import re
p = re.compile(r'(\d+)')  # a pattern for a number

for line in file :
    if num in p.findall(line) :
        print line

regular expression will return you all numbers in a line as a list, for example:

>>> re.compile(r'(\d+)').findall('123kh234hi56h9234hj29kjh290')
['123', '234', '56', '9234', '29', '290']

so you don't match '200' or '220' for '20'.

JavaScript string with new line - but not using \n

I think they using \n anyway even couse it not visible, or maybe they using \r. So just replace \n or \r with <br/>

How to run Spring Boot web application in Eclipse itself?

You can also use the "Spring Boot App" run configuration. For that you'll need to install the Spring Tool Suite plug-in for Eclipse (STS).

What is the point of WORKDIR on Dockerfile?

You can think of WORKDIR like a cd inside the container (it affects commands that come later in the Dockerfile, like the RUN command). If you removed WORKDIR in your example above, RUN npm install wouldn't work because you would not be in the /usr/src/app directory inside your container.

I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY is a relative path, so if you move your Dockerfile you may need to update those COPY commands.

How can I get last characters of a string

The Substr function allows you to use a minus to get the last character.

var string = "hello";
var last = string.substr(-1);

It's very flexible. For example:

// Get 2 characters, 1 character from end
// The first part says how many characters
// to go back and the second says how many
// to go forward. If you don't say how many
// to go forward it will include everything
var string = "hello!";
var lasttwo = string.substr(-3,2);
// = "lo"

How to use sed to extract substring

grep was born to extract things:

grep -Po 'name="\K[^"]*'

test with your data:

kent$  echo '<parameter name="PortMappingEnabled" access="readWrite" type="xsd:boolean"></parameter>
  <parameter name="PortMappingLeaseDuration" access="readWrite" activeNotify="canDeny" type="xsd:unsignedInt"></parameter>
  <parameter name="RemoteHost" access="readWrite"></parameter>
  <parameter name="ExternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
  <parameter name="ExternalPortEndRange" access="readWrite" type="xsd:unsignedInt"></parameter>
  <parameter name="InternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
  <parameter name="PortMappingProtocol" access="readWrite"></parameter>
  <parameter name="InternalClient" access="readWrite"></parameter>
  <parameter name="PortMappingDescription" access="readWrite"></parameter>
'|grep -Po 'name="\K[^"]*'
PortMappingEnabled
PortMappingLeaseDuration
RemoteHost
ExternalPort
ExternalPortEndRange
InternalPort
PortMappingProtocol
InternalClient
PortMappingDescription

Disable browser cache for entire ASP.NET website

HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();

All requests get routed through default.aspx first - so assuming you can just pop in code behind there.

How to display tables on mobile using Bootstrap?

All tables within bootstrap stretch according to the container they're in. You can put your tables inside a .span element to control the size. This SO Question may help you out

Why do Twitter Bootstrap tables always have 100% width?

img onclick call to JavaScript function

This should work(with or without 'javascript:' part):

<img onclick="javascript:exportToForm('1.6','55','10','50','1')" src="China-Flag-256.png" />
<script>
function exportToForm(a, b, c, d, e) {
     alert(a, b);
 }
</script>

removing html element styles via javascript

getElementById("id").removeAttribute("style");

if you are using jQuery then

$("#id").removeClass("classname");

How to remove leading whitespace from each line in a file

For this specific problem, something like this would work:

$ sed 's/^ *//g' < input.txt > output.txt

It says to replace all spaces at the start of a line with nothing. If you also want to remove tabs, change it to this:

$ sed 's/^[ \t]+//g' < input.txt > output.txt

The leading "s" before the / means "substitute". The /'s are the delimiters for the patterns. The data between the first two /'s are the pattern to match, and the data between the second and third / is the data to replace it with. In this case you're replacing it with nothing. The "g" after the final slash means to do it "globally", ie: over the entire file rather than on only the first match it finds.

Finally, instead of < input.txt > output.txt you can use the -i option which means to edit the file "in place". Meaning, you don't need to create a second file to contain your result. If you use this option you will lose your original file.

PHP if not statements

You could also try:

if ((!isset($action)) || !($action == "add" || $action == "delete")) {
  // Do your stuff
}

Suppress console output in PowerShell

Try redirecting the output like this:

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1

Django gives Bad Request (400) when DEBUG = False

With DEBUG = False in you settings file, you also need ALLOWED_HOST list set up. Try including ALLOWED_HOST = ['127.0.0.1', 'localhost', 'www.yourdomain.com']

Otherwise you might receive a Bad Request(400) error from django.

NameError: global name 'xrange' is not defined in Python 3

You are trying to run a Python 2 codebase with Python 3. xrange() was renamed to range() in Python 3.

Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond xrange() vs. range().

For the record, what you are seeing is not a syntax error but a runtime exception instead.


If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range. (Take into account that you may have to update any existing range() use in the Python 2 codebase with list(range(...)) to ensure you still get a list object in Python 3):

try:
    # Python 2
    xrange
except NameError:
    # Python 3, xrange is now named range
    xrange = range

# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))

or replace all uses of xrange(...) with range(...) in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:

try:
    # Python 2 forward compatibility
    range = xrange
except NameError:
    pass

# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).

The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

According to this: https://www.simplified.guide/phpmyadmin/enable-login-without-password

This $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; should be added twice in /etc/phpmyadmin/config.inc.php

if (!empty($dbname)) {
    // other configuration options
    $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
    // it should be placed before the following line
    $i++;
}

// other configuration options
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

$_POST not working. "Notice: Undefined index: username..."

first of all,

be sure that there is a post

if(isset($_POST['username'])) { 
    // check if the username has been set
}

second, and most importantly, sanitize the data, meaning that

$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";

is deadly dangerous, instead use

$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";

and please research the subject sql injection

How to commit and rollback transaction in sql server?

Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.

Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ...... 

how to copy only the columns in a DataTable to another DataTable?

Datatable.Clone is slow for large tables. I'm currently using this:

Dim target As DataTable = 
    New DataView(source, "1=2", Nothing, DataViewRowState.CurrentRows)
    .ToTable()

Note that this only copies the structure of source table, not the data.

Running multiple commands in one line in shell

Try this..

cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple

Python way to clone a git repository

This is the sample code for gitpull and gitpush using gitpython module.

import os.path
from git import *
import git, os, shutil
# create local Repo/Folder
UPLOAD_FOLDER = "LocalPath/Folder"
if not os.path.exists(UPLOAD_FOLDER):
  os.makedirs(UPLOAD_FOLDER)
  print(UPLOAD_FOLDER)
new_path = os.path.join(UPLOADFOLDER)
DIR_NAME = new_path
REMOTE_URL = "GitURL"  # if you already connected with server you dont need to give 
any credential
# REMOTE_URL looks "[email protected]:path of Repo"
# code for clone
class git_operation_clone():
  try:
    def __init__(self):
        self.DIR_NAME = DIR_NAME
        self.REMOTE_URL = REMOTE_URL

    def git_clone(self):

        if os.path.isdir(DIR_NAME):
            shutil.rmtree(DIR_NAME)
        os.mkdir(DIR_NAME)
        repo = git.Repo.init(DIR_NAME)
        origin = repo.create_remote('origin', REMOTE_URL)
        origin.fetch()
        origin.pull(origin.refs[0].remote_head)
  except Exception as e:
      print(str(e))
# code for push
class git_operation_push():
  def git_push_file(self):
    try:
        repo = Repo(DIR_NAME)
        commit_message = 'work in progress'
        # repo.index.add(u=True)
        repo.git.add('--all')
        repo.index.commit(commit_message)
        origin = repo.remote('origin')
        origin.push('master')
        repo.git.add(update=True)
        print("repo push succesfully")
    except Exception as e:
        print(str(e))
if __name__ == '__main__':
   a = git_operation_push()
   git_operation_push.git_push_file('')
   git_operation_clone()
   git_operation_clone.git_clone('')

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

Arduino IDE can't find ESP8266WiFi.h file

When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.

Open Arduino IDE and go to files and click on the preference in the Arduino IDE.

Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.

Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.

You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.

Using variables in Nginx location rules

You can't. Nginx doesn't really support variables in config files, and its developers mock everyone who ask for this feature to be added:

"[Variables] are rather costly compared to plain static configuration. [A] macro expansion and "include" directives should be used [with] e.g. sed + make or any other common template mechanism." http://nginx.org/en/docs/faq/variables_in_config.html

You should either write or download a little tool that will allow you to generate config files from placeholder config files.

Update The code below still works, but I've wrapped it all up into a small PHP program/library called Configurator also on Packagist, which allows easy generation of nginx/php-fpm etc config files, from templates and various forms of config data.

e.g. my nginx source config file looks like this:

location  / {
    try_files $uri /routing.php?$args;
    fastcgi_pass   unix:%phpfpm.socket%/php-fpm-www.sock;
    include       %mysite.root.directory%/conf/fastcgi.conf;
}

And then I have a config file with the variables defined:

phpfpm.socket=/var/run/php-fpm.socket
mysite.root.directory=/home/mysite

And then I generate the actual config file using that. It looks like you're a Python guy, so a PHP based example may not help you, but for anyone else who does use PHP:

<?php

require_once('path.php');

$filesToGenerate = array(
    'conf/nginx.conf' => 'autogen/nginx.conf',
    'conf/mysite.nginx.conf' => 'autogen/mysite.nginx.conf',
    'conf/mysite.php-fpm.conf' => 'autogen/mysite.php-fpm.conf',
    'conf/my.cnf' => 'autogen/my.cnf',
);

$environment = 'amazonec2';

if ($argc >= 2){
    $environmentRequired = $argv[1];

    $allowedVars = array(
        'amazonec2',
        'macports',
    );

    if (in_array($environmentRequired, $allowedVars) == true){
        $environment = $environmentRequired;
    }
}
else{
    echo "Defaulting to [".$environment."] environment";
}

$config = getConfigForEnvironment($environment);

foreach($filesToGenerate as $inputFilename => $outputFilename){
    generateConfigFile(PATH_TO_ROOT.$inputFilename, PATH_TO_ROOT.$outputFilename, $config);
}


function    getConfigForEnvironment($environment){
    $config = parse_ini_file(PATH_TO_ROOT."conf/deployConfig.ini", TRUE);
    $configWithMarkers = array();
    foreach($config[$environment] as $key => $value){
        $configWithMarkers['%'.$key.'%'] = $value;
    }

    return  $configWithMarkers;
}


function    generateConfigFile($inputFilename, $outputFilename, $config){

    $lines = file($inputFilename);

    if($lines === FALSE){
        echo "Failed to read [".$inputFilename."] for reading.";
        exit(-1);
    }

    $fileHandle = fopen($outputFilename, "w");

    if($fileHandle === FALSE){
        echo "Failed to read [".$outputFilename."] for writing.";
        exit(-1);
    }

    $search = array_keys($config);
    $replace = array_values($config);

    foreach($lines as $line){
        $line = str_replace($search, $replace, $line);
        fwrite($fileHandle, $line);
    }

    fclose($fileHandle);
}

?>

And then deployConfig.ini looks something like:

[global]

;global variables go here.

[amazonec2]
nginx.log.directory = /var/log/nginx
nginx.root.directory = /usr/share/nginx
nginx.conf.directory = /etc/nginx
nginx.run.directory  = /var/run
nginx.user           = nginx

[macports]
nginx.log.directory = /opt/local/var/log/nginx
nginx.root.directory = /opt/local/share/nginx
nginx.conf.directory = /opt/local/etc/nginx
nginx.run.directory  = /opt/local/var/run
nginx.user           = _www

How to set Default Controller in asp.net MVC 4 & MVC 5

In case you have only one controller and you want to access every action on root you can skip controller name like this

routes.MapRoute(
        "Default", 
        "{action}/{id}", 
        new { controller = "Home", action = "Index", 
        id = UrlParameter.Optional }
);

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

Consider this array:

$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
  • To remove an element using the array key:

    // To unset an element from array using Key:
    unset($arr["key2"]);
    var_dump($arr);
    // output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
    
  • To remove element by value:

    // remove an element by value:
    $arr = array_diff($arr, ["value1"]);
    var_dump($arr);
    // output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" } 
    

read more about array_diff: http://php.net/manual/en/function.array-diff.php

  • To remove an element by using index:

    array_splice($arr, 1, 1);
    var_dump($arr);
    // array(1) { ["key3"]=> string(6) "value3" } 
    

read more about array_splice: http://php.net/manual/en/function.array-splice.php

How can I wrap text in a label using WPF?

To wrap text in the label control, change the the template of label as follows:

<Style x:Key="ErrorBoxStyle" TargetType="{x:Type Label}">
    <Setter Property="BorderBrush" Value="#FFF08A73"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="Foreground" Value="Red"/>
    <Setter Property="Background" Value="#FFFFE3DF"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Padding" Value="5"/>
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="VerticalContentAlignment" Value="Top"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Label}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" CornerRadius="5" HorizontalAlignment="Stretch">
                     
                    <TextBlock TextWrapping="Wrap" Text="{TemplateBinding Content}"/>
                </Border>
                    
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Short description of the scoping rules?

Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply.)

LEGB Rule

  • Local — Names assigned in any way within a function (def or lambda), and not declared global in that function

  • Enclosing-function — Names assigned in the local scope of any and all statically enclosing functions (def or lambda), from inner to outer

  • Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file

  • Built-in (Python) — Names preassigned in the built-in names module: open, range, SyntaxError, etc

So, in the case of

code1
class Foo:
    code2
    def spam():
        code3
        for code4:
            code5
            x()

The for loop does not have its own namespace. In LEGB order, the scopes would be

  • L: Local in def spam (in code3, code4, and code5)
  • E: Any enclosing functions (if the whole example were in another def)
  • G: Were there any x declared globally in the module (in code1)?
  • B: Any builtin x in Python.

x will never be found in code2 (even in cases where you might expect it would, see Antti's answer or here).

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

check below link in which you can download suitable AjaxControlToolkit which suits your .NET version.

http://ajaxcontroltoolkit.codeplex.com/releases/view/43475

AjaxControlToolkit.Binary.NET4.zip - used for .NET 4.0

AjaxControlToolkit.Binary.NET35.zip - used for .NET 3.5

Clearing NSUserDefaults

I love extensions when they make the code cleaner:

extension NSUserDefaults {
    func clear() {
        guard let domainName = NSBundle.mainBundle().bundleIdentifier else {
            return
        }

        self.removePersistentDomainForName(domainName)
    }
}

Swift 5

extension UserDefaults {
    func clear() {
        guard let domainName = Bundle.main.bundleIdentifier else {
            return
        }
        removePersistentDomain(forName: domainName)
        synchronize()
    }
}

Get size of folder or file

  • Works for Android and Java
  • Works for both folders and files
  • Checks for null pointer everywhere where needed
  • Ignores symbolic link aka shortcuts
  • Production ready!

Source code:

   public long fileSize(File root) {
        if(root == null){
            return 0;
        }
        if(root.isFile()){
            return root.length();
        }
        try {
            if(isSymlink(root)){
                return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }

        long length = 0;
        File[] files = root.listFiles();
        if(files == null){
            return 0;
        }
        for (File file : files) {
            length += fileSize(file);
        }

        return length;
    }

    private static boolean isSymlink(File file) throws IOException {
        File canon;
        if (file.getParent() == null) {
            canon = file;
        } else {
            File canonDir = file.getParentFile().getCanonicalFile();
            canon = new File(canonDir, file.getName());
        }
        return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
    }

Laravel 5 Carbon format datetime

Try that:

$createdAt = Carbon::parse(date_format($item['created_at'],'d/m/Y H:i:s');
$createdAt= $createdAt->format('M d Y');

Performing Inserts and Updates with Dapper

We are looking at building a few helpers, still deciding on APIs and if this goes in core or not. See: https://code.google.com/archive/p/dapper-dot-net/issues/6 for progress.

In the mean time you can do the following

val = "my value";
cnn.Execute("insert into Table(val) values (@val)", new {val});

cnn.Execute("update Table set val = @val where Id = @id", new {val, id = 1});

etcetera

See also my blog post: That annoying INSERT problem

Update

As pointed out in the comments, there are now several extensions available in the Dapper.Contrib project in the form of these IDbConnection extension methods:

T Get<T>(id);
IEnumerable<T> GetAll<T>();
int Insert<T>(T obj);
int Insert<T>(Enumerable<T> list);
bool Update<T>(T obj);
bool Update<T>(Enumerable<T> list);
bool Delete<T>(T obj);
bool Delete<T>(Enumerable<T> list);
bool DeleteAll<T>();

How to launch an Activity from another Application in Android

Here is my example of launching bar/QR code scanner from my app if someone finds it useful

Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");

try 
{
    startActivityForResult(intent, SCAN_REQUEST_CODE);
} 
catch (ActivityNotFoundException e) 
{
    //implement prompt dialog asking user to download the package
    AlertDialog.Builder downloadDialog = new AlertDialog.Builder(this);
    downloadDialog.setTitle(stringTitle);
    downloadDialog.setMessage(stringMessage);
    downloadDialog.setPositiveButton("yes",
            new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialogInterface, int i) 
                {
                    Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    try
                    {
                        myActivity.this.startActivity(intent);
                    }
                    catch (ActivityNotFoundException e)
                    {
                        Dialogs.this.showAlert("ERROR", "Google Play Market not found!");
                    }
                }
            });
    downloadDialog.setNegativeButton("no",
            new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int i) 
                {
                    dialog.dismiss();
                }
            });
    downloadDialog.show();
}

Why does Firebug say toFixed() is not a function?

toFixed isn't a method of non-numeric variable types. In other words, Low and High can't be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat() (or parseInt() with a radix, if it's an integer) will allow you to convert different variable types to numbers which will enable the toFixed() function to work.

var Low  = parseFloat($SliderValFrom.val()),
    High = parseFloat($SliderValTo.val());

MsgBox "" vs MsgBox() in VBScript

You are just using a single parameter inside the function hence it is working fine in both the cases like follows:

MsgBox "Hello world!"
MsgBox ("Hello world!")

But when you'll use more than one parameter, In VBScript method will parenthesis will throw an error and without parenthesis will work fine like:

MsgBox "Hello world!", vbExclamation

The above code will run smoothly but

MsgBox ("Hello world!", vbExclamation)

will throw an error. Try this!! :-)

Check if checkbox is NOT checked on click - jQuery

Check out some of the answers to this question - I think it might apply to yours:

how to run click function after default behaviour of a element

I think you're running into an inconsistency in the browser implementation of the onclick function. Some choose to toggle the checkbox before the event is fired and some after.

How to convert hashmap to JSON object in Java

You can use Gson. This library provides simple methods to convert Java objects to JSON objects and vice-versa.

Example:

GsonBuilder gb = new GsonBuilder();
Gson gson = gb.serializeNulls().create();
gson.toJson(object);

You can use a GsonBuilder when you need to set configuration options other than the default. In the above example, the conversion process will also serialize null attributes from object.

However, this approach only works for non-generic types. For generic types you need to use toJson(object, Type).

More information about Gson here.

Remember that the object must implement the Serializable interface.

Jenkins - how to build a specific branch

Best solution can be:

Add a string parameter in the existing job enter image description here

Then in the Source Code Management section update Branches to build to use the string parameter you defined enter image description here

If you see a checkbox labeled Lightweight checkout, make sure it is unchecked.

The configuration indicated in the images will tell the jenkins job to use master as the default branch, and for manual builds it will ask you to enter branch details (FYI: by default it's set to master)enter image description here

How to use System.Net.HttpClient to post a complex type?

This is the code I wound up with, based upon the other answers here. This is for an HttpPost that receives and responds with complex types:

Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync(
                       strMyHttpPostURL,
                       new MyComplexObject { Param1 = param1, Param2 = param2}).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
                    //debug:
                    //String s = response.Result.Content.ReadAsStringAsync().Result;
                    MyOtherComplexType moct = (MyOtherComplexType)JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result, typeof(MyOtherComplexType));

Determining Referer in PHP

What I have found best is a CSRF token and save it in the session for links where you need to verify the referrer.

So if you are generating a FB callback then it would look something like this:

$token = uniqid(mt_rand(), TRUE);
$_SESSION['token'] = $token;
$url = "http://example.com/index.php?token={$token}";

Then the index.php will look like this:

if(empty($_GET['token']) || $_GET['token'] !== $_SESSION['token'])
{
    show_404();
} 

//Continue with the rest of code

I do know of secure sites that do the equivalent of this for all their secure pages.

Insert multiple rows into single column

INSERT INTO hr.employees (location_id) VALUE (1000) WHERE first_name LIKE '%D%';

let me know if there is any problem in this statement.

Insert new item in array on any position in PHP

This is what worked for me for the associative array:

/*
 * Inserts a new key/value after the key in the array.
 *
 * @param $key
 *   The key to insert after.
 * @param $array
 *   An array to insert in to.
 * @param $new_key
 *   The key to insert.
 * @param $new_value
 *   An value to insert.
 *
 * @return
 *   The new array if the key exists, FALSE otherwise.
 *
 * @see array_insert_before()
 */
function array_insert_after($key, array &$array, $new_key, $new_value) {
  if (array_key_exists($key, $array)) {
    $new = array();
    foreach ($array as $k => $value) {
      $new[$k] = $value;
      if ($k === $key) {
        $new[$new_key] = $new_value;
      }
    }
    return $new;
  }
  return FALSE;
}

The function source - this blog post. There's also handy function to insert BEFORE specific key.

Java Singleton and Synchronization

You can also use static code block to instantiate the instance at class load and prevent the thread synchronization issues.

public class MySingleton {

  private static final MySingleton instance;

  static {
     instance = new MySingleton();
  }

  private MySingleton() {
  }

  public static MySingleton getInstance() {
    return instance;
  }

}

Checking Maven Version

On terminal type mvn -v and the output will look like the image shown below

enter image description here

BigDecimal to string

The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .

like this:

BigDecimal bd1 = new BigDecimal("10.0001");

now, you can display bd1 as 10.0001

So simple. GOOD LUCK.

"R cannot be resolved to a variable"?

My problem was strange and took some time to find. Somehow the package of the src file changed so that the last entry in the package was deleted. So for example initially my class MyActivity.java was in package com.abc.client.test.app but after I added a user permission, the app got removed and the package was renamed to com.abc.client.test. I don't know how it happened. Renaming the package and putting the java file in the correct place fixed the problem.

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

Change the set of installed JREs in your eclipse. Window > Preferences > Java > Installed JREs, change the location of jre to %JAVA_HOME%/jre, but not something like C:\Program Files\Java\jre7

How to set the env variable for PHP?

You need to put the directory that has php.exe in you WAMP installation into your PATH. It is usually something like C:\wamp\xampp\php

How to see JavaDoc in IntelliJ IDEA?

The closest to Eclipse will be Ctrl+Button2 Click (Scroll click)

It's called Quick Doc in IntelliJ, I wish guys from JetBrains one day add quick doc like Eclipse with Ctrl+Mouse Move it's so much better.

In my case only with only mouse move is a bit annoying, so if you search in Preferences/Settings --> Keymap for "quick documentation" you will find:

  • Win-Linux: "Ctrl+Q" and "Ctrl+Button2 Click" (Scroll click)
  • Mac: "Ctrl+J" and "Ctrl+Button2 Click" (Scroll click)

Convert integer to class Date

You can use ymd from lubridate

lubridate::ymd(v)
#[1] "2008-11-01"

Or anytime::anydate

anytime::anydate(v)
#[1] "2008-11-01"

Bootstrap: adding gaps between divs

Starting from Bootstrap v4 you can simply add the following to your div class attribute: mt-2 (margin top 2)

<div class="mt-2 col-md-12">
        This will have a two-point top margin!
</div>

More examples are given in the docs: Bootstrap v4 docs

Check if object exists in JavaScript

zero and null are implicit pointers. If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.

if(obj) console.log("exists");

I didn't see request for a not or else there for it is not included as. As much as i love extra content which doesn't fit into the question. Lets keep it simple.

Validate form field only on submit or user input

You can use angularjs form state form.$submitted. Initially form.$submitted value will be false and will became true after successful form submit.

Remove All Event Listeners of Specific Type

In the extreme case of not knowing which callback is attached to a window listener, an handler can be wrapper around window addEventListener and a variable can store ever listeners to properly remove each one of those through a removeAllEventListener('scroll') for example.

var listeners = {};

var originalEventListener = window.addEventListener;
window.addEventListener = function(type, fn, options) {
    if (!listeners[type])
        listeners[type] = [];

    listeners[type].push(fn);
    return originalEventListener(type, fn, options);
}

var removeAllEventListener = function(type) {
    if (!listeners[type] || !listeners[type].length)
        return;

    for (let i = 0; i < listeners[type].length; i++)
        window.removeEventListener(type, listeners[type][i]);
}

Parse query string in JavaScript

You can also use the excellent URI.js library by Rodney Rehm. Here's how:-

var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
    alert(qs.dest); // == aboutus.aspx

And to parse the query string of current page:-

var $_GET = URI(document.URL).query(true); // ala PHP
    alert($_GET['dest']); // == aboutus.aspx 

The following untracked working tree files would be overwritten by merge, but I don't care

For those who don't know, git ignores uppercase/lowercase name differences in files and folders. This turns out to be a nightmare when you rename them to the exact same name with a different case.

I encountered this issue when I renamed a folder from "Petstore" to "petstore" (uppercase to lowercase). I had edited my .git/config file to stop ignoring case, made changes, squashed my commits, and stashed my changes to move to a different branch. I could not apply my stashed changes to this other branch.

The fix that I found that worked was to temporarily edit my .git/config file to temporarily ignore case again. This caused git stash apply to succeed. Then, I changed ignoreCase back to false. I then added everything except for the new files in the petstore folder which git oddly claimed were deleted, for whatever reason. I committed my changes, then ran git reset --hard HEAD to get rid of those untracked new files. My commit appeared exactly as expected: the files in the folder were renamed.

I hope that this helps you avoid my same nightmare.

Git push error: Unable to unlink old (Permission denied)

FWIW - I had a similar problem and I'm not sure if this alleviated it (beyond the permission mod): Closing Eclipse that was using the branch with this problem.

Read a local text file using Javascript

You can use a FileReader object to read text file here is example code:

  <div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</script>

FileProvider - IllegalArgumentException: Failed to find configured root

The following change in xml file_paths file worked for me.

 <external-files-path name="my_images" path="Pictures"/>
 <external-files-path name="my_movies" path="Movies"/>

Why is my Spring @Autowired field null?

UPDATE: Really smart people were quick to point on this answer, which explains the weirdness, described below

ORIGINAL ANSWER:

I don't know if it helps anyone, but I was stuck with the same problem even while doing things seemingly right. In my Main method, I have a code like this:

ApplicationContext context =
    new ClassPathXmlApplicationContext(new String[] {
        "common.xml",
        "token.xml",
        "pep-config.xml" });
    TokenInitializer ti = context.getBean(TokenInitializer.class);

and in a token.xml file I've had a line

<context:component-scan base-package="package.path"/>

I noticed that the package.path does no longer exist, so I've just dropped the line for good.

And after that, NPE started coming in. In a pep-config.xml I had just 2 beans:

<bean id="someAbac" class="com.pep.SomeAbac" init-method="init"/>
<bean id="settings" class="com.pep.Settings"/>

and SomeAbac class has a property declared as

@Autowired private Settings settings;

for some unknown reason, settings is null in init(), when <context:component-scan/> element is not present at all, but when it's present and has some bs as a basePackage, everything works well. This line now looks like this:

<context:component-scan base-package="some.shit"/>

and it works. May be someone can provide an explanation, but for me it's enough right now )

What does "static" mean in C?

Short answer ... it depends.

  1. Static defined local variables do not lose their value between function calls. In other words they are global variables, but scoped to the local function they are defined in.

  2. Static global variables are not visible outside of the C file they are defined in.

  3. Static functions are not visible outside of the C file they are defined in.

correct way to use super (argument passing)

As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

class A(object):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(*args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(*args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(*args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

How to generate Javadoc HTML files in Eclipse?

This is a supplement answer related to the OP:

An easy and reliable solution to add Javadocs comments in Eclipse:

  1. Go to Help > Eclipse Marketplace....
  2. Find "JAutodoc".
  3. Install it and restart Eclipse.

To use this tool, right-click on class and click on JAutodoc.

pandas DataFrame: replace nan values with average of columns

In [16]: df = DataFrame(np.random.randn(10,3))

In [17]: df.iloc[3:5,0] = np.nan

In [18]: df.iloc[4:6,1] = np.nan

In [19]: df.iloc[5:8,2] = np.nan

In [20]: df
Out[20]: 
          0         1         2
0  1.148272  0.227366 -2.368136
1 -0.820823  1.071471 -0.784713
2  0.157913  0.602857  0.665034
3       NaN -0.985188 -0.324136
4       NaN       NaN  0.238512
5  0.769657       NaN       NaN
6  0.141951  0.326064       NaN
7 -1.694475 -0.523440       NaN
8  0.352556 -0.551487 -1.639298
9 -2.067324 -0.492617 -1.675794

In [22]: df.mean()
Out[22]: 
0   -0.251534
1   -0.040622
2   -0.841219
dtype: float64

Apply per-column the mean of that columns and fill

In [23]: df.apply(lambda x: x.fillna(x.mean()),axis=0)
Out[23]: 
          0         1         2
0  1.148272  0.227366 -2.368136
1 -0.820823  1.071471 -0.784713
2  0.157913  0.602857  0.665034
3 -0.251534 -0.985188 -0.324136
4 -0.251534 -0.040622  0.238512
5  0.769657 -0.040622 -0.841219
6  0.141951  0.326064 -0.841219
7 -1.694475 -0.523440 -0.841219
8  0.352556 -0.551487 -1.639298
9 -2.067324 -0.492617 -1.675794

Why doesn't Java offer operator overloading?

I think that people making decisions simply forgot about complex values, matrix algebra, set theory and other cases when overloading would allow to use the standard notation without building everything into the language. Anyway, only mathematically oriented software really benefits from such features. A generic customer application almost never needs them.

They arguments about the unnecessary obfuscation are obviously valid when a programmer defines some program-specific operator where it could be the function instead. A name of the function, when clearly visible, provides the hint that it does. Operator is a function without the readable name.

Java is generally designed about philosophy that some extra verbosity is not bad as it makes the code more readable. Constructs that do the same just have less code to type in used to be called a "syntax sugar" in the past. This is very different from the Python philosophy, for instance, where shorter is near always seen as better, even if providing less context for the second reader.

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

How can we redirect a Java program console output to multiple files?

We can do this by setting out variable of System class in the following way

System.setOut(new PrintStream(new FileOutputStream("Path to output file"))). Also You need to close or flush 'out'(System.out.close() or System.out.flush()) variable so that you don't end up missing some output.

Source : http://xmodulo.com/how-to-save-console-output-to-file-in-eclipse.html

Unresponsive KeyListener for JFrame

Hmm.. what class is your constructor for? Probably some class extending JFrame? The window focus should be at the window, of course but I don't think that's the problem.

I expanded your code, tried to run it and it worked - the key presses resulted as print output. (run with Ubuntu through Eclipse):

public class MyFrame extends JFrame {
    public MyFrame() {
        System.out.println("test");
        addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {
                System.out.println("tester");
            }

            public void keyReleased(KeyEvent e) {
                System.out.println("2test2");
            }

            public void keyTyped(KeyEvent e) {
                System.out.println("3test3");
            }
        });
    }

    public static void main(String[] args) {
        MyFrame f = new MyFrame();
        f.pack();
        f.setVisible(true);
    }
}

Android: where are downloaded files saved?

In my experience all the files which i have downloaded from internet,gmail are stored in

/sdcard/download

on ics

/sdcard/Download

You can access it using

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

SOLUTION

This means that you are missing the right for using it. Create it with Netsh Commands for Hypertext Transfer Protocol > add urlacl.

1) Open "Command Line Interface (CLI)" called "Command shell" with Win+R write "cmd"

2) Open CLI windows like administrator with mouse context menu on opened windows or icon "Run as administrator"

3) Insert command to register url

netsh http add urlacl url=http://{ip_addr}:{port}/ user=everyone

NOTE:

How to find if div with specific id exists in jQuery?

The most simple way is..

if(window["myId"]){
    // ..
}

This is also part of HTML5 specs: https://www.w3.org/TR/html5/single-page.html#accessing-other-browsing-contexts#named-access-on-the-window-object

window[name]
    Returns the indicated element or collection of elements.

When would you use the different git merge strategies?

As the answers above are not showing all strategy details. For example, some answer is missing the details about the import resolve option and the recursive which has many sub options as ours, theirs, patience, renormalize, etc.

Therefore, I would recommend to visit the official git documentation which explains all the possible features features:

https://git-scm.com/docs/merge-strategies

Output single character in C

Be careful of difference between 'c' and "c"

'c' is a char suitable for formatting with %c

"c" is a char* pointing to a memory block with a length of 2 (with the null terminator).

How to install easy_install in Python 2.7.1 on Windows 7

Look for the official 2.7 setuptools installer (which contains easy_install). You only need to install from sources for windows 64 bits.

How to terminate the script in JavaScript?

"exit" functions usually quit the program or script along with an error message as paramete. For example die(...) in php

die("sorry my fault, didn't mean to but now I am in byte nirvana")

The equivalent in JS is to signal an error with the throw keyword like this:

throw new Error();

You can easily test this:

var m = 100;
throw '';
var x = 100;

x
>>>undefined
m
>>>100

mysql server port number

try

$conn = mysql_connect($host, $username, $password, $port);

Retrieve column names from java.sql.ResultSet

import java.sql.*;

public class JdbcGetColumnNames {

    public static void main(String args[]) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/komal", "root", "root");

            st = con.createStatement();

            String sql = "select * from person";
            rs = st.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();

            int rowCount = metaData.getColumnCount();

            System.out.println("Table Name : " + metaData.getTableName(2));
            System.out.println("Field  \tDataType");

            for (int i = 0; i < rowCount; i++) {
                System.out.print(metaData.getColumnName(i + 1) + "  \t");
                System.out.println(metaData.getColumnTypeName(i + 1));
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Table Name : person Field DataType id VARCHAR cname VARCHAR dob DATE

Activating Anaconda Environment in VsCode

If you need an independent environment for your project: Install your environment to your project folder using the --prefix option:

conda create --prefix C:\your\workspace\root\awesomeEnv\ python=3

In VSCode launch.json configuration set your "pythonPath" to:

"pythonPath":"${workspaceRoot}/awesomeEnv/python.exe"

How to return an array from an AJAX call?

well, I know that I'm a bit too late, but I tried all of your solutions and with no success! So here is how I managed to do it. First of all, I'm working on an Asp.Net MVC project. The Only thing I changed was in my c# method getInvitation:

public ActionResult getInvitation (Guid s_ID)
{
    using (var db = new cRM_Verband_BWEntities())
    {
        var listSidsMit = (from data in db.TERMINEINLADUNGEN where data.RECID_KOMMUNIKATIONEN == s_ID select data.RECID_MITARBEITER.ToString()).ToArray();
        return Json(listSidsMit);
    }
}

SuccessFunction in JS :

function successFunction(result) {
    console.log(result);
}

I changed the Method Type from string[] to ActionResult and of course at the end I wrapped my array listSidsMit with the Json method.

What is the difference between SAX and DOM?

Here in simpler words:

DOM

  • Tree model parser (Object based) (Tree of nodes).

  • DOM loads the file into the memory and then parse- the file.

  • Has memory constraints since it loads the whole XML file before parsing.

  • DOM is read and write (can insert or delete nodes).

  • If the XML content is small, then prefer DOM parser.

  • Backward and forward search is possible for searching the tags and evaluation of the information inside the tags. So this gives the ease of navigation.

  • Slower at run time.

SAX

  • Event based parser (Sequence of events).

  • SAX parses the file as it reads it, i.e. parses node by node.

  • No memory constraints as it does not store the XML content in the memory.

  • SAX is read only i.e. can’t insert or delete the node.

  • Use SAX parser when memory content is large.

  • SAX reads the XML file from top to bottom and backward navigation is not possible.

  • Faster at run time.

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

Purpose of returning by const value?

In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that + returned a non-const value, and you could write:

(a + b).expensive();

In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.

In summary, there is a rationale for this practice, but it is essentially obsolete.

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Service Temporarily Unavailable Magento?

If removing the flag shows service temporary unavailable. Go to "http://localhost.com/downloader" and unisntall slider banner,BusinessDecision_Interaktingslider,lightbox2 and anotherone that I dont remember.

Display an image into windows forms

Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:

  • Like you are doing.
  • Using ImageLocation property of the PictureBox like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "../SamuderaJayaMotor.png";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    
  • Using an image from the web like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    

And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.

Why doesn't java.util.Set have get(int index)?

That's true, element in Set are not ordered, by definition of the Set Collection. So they can't be access by an index.

But why don't we have a get(object) method, not by providing the index as parameter, but an object that is equal to the one we are looking for? By this way, we can access the data of the element inside the Set, just by knowing its attributes used by the equal method.

How to print variables in Perl

You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.

print $ids should be a fairly hard statement to mess up, but it is possible. Possible reasons:

  1. $ids is undefined. Gives the warning undefined value in print
  2. $ids is out of scope. With use strict, gives fatal warning Global variable $ids needs explicit package name, and otherwise the undefined warning from above.
  3. You forgot a semi-colon at the end of the line.
  4. You tried to do print $ids $nIds, in which case perl thinks that $ids is supposed to be a filehandle, and you get an error such as print to unopened filehandle.

Explanations

1: Should not happen. It might happen if you do something like this (assuming you are not using strict):

my $var;
while (<>) {
    $Var .= $_;
}
print $var;

Gives the warning for undefined value, because $Var and $var are two different variables.

2: Might happen, if you do something like this:

if ($something) {
    my $var = "something happened!";
}
print $var;

my declares the variable inside the current block. Outside the block, it is out of scope.

3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings.

4: Also a common mistake. There are a number of ways to correctly print two variables in the same print statement:

print "$var1 $var2";  # concatenation inside a double quoted string
print $var1 . $var2;  # concatenation
print $var1, $var2;   # supplying print with a list of args

Lastly, some perl magic tips for you:

use strict;
use warnings;

# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;

# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;

my $ids  = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";

Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.

Variations:

  • print "@file" is equivalent to $ids = join(' ',@file); print $ids;
  • $#file will return the last index in @file. Since arrays usually start at 0, $#file + 1 is equivalent to scalar @file.

You can also do:

my $ids;
do {
    local $/;
    $ids = <$fh>;
}

By temporarily "turning off" $/, the input record separator, i.e. newline, you will make <$fh> return the entire file. What <$fh> really does is read until it finds $/, then return that string. Note that this will preserve the newlines in $ids.

Line-by-line solution:

open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
    chomp;
    $ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.

How can I find my Apple Developer Team id and Team Agent Apple ID?

For personal teams

grep DEVELOPMENT_TEAM MyProject.xcodeproj/project.pbxproj

should give you the team ID

DEVELOPMENT_TEAM = ZU88ND8437;

Mongoose.js: Find user by username LIKE value

For those that were looking for a solution here it is:

var name = 'Peter';
model.findOne({name: new RegExp('^'+name+'$', "i")}, function(err, doc) {
  //Do your action here..
});

Convert String[] to comma separated string in java

Extention for prior Java 8 solution

String result = String.join(",", name);

If you need prefix or/ and suffix for array values

 StringJoiner joiner = new StringJoiner(",");
 for (CharSequence cs: name) {
     joiner.add("'" + cs + "'");
 }
 return joiner.toString();

Or simple method concept

  public static String genInValues(String delimiter, String prefix, String suffix, String[] name) {
    StringJoiner joiner = new StringJoiner(delimiter);
    for (CharSequence cs: name) {
      joiner.add(prefix + cs + suffix);
    }
    return joiner.toString();
  }

For example

For Oracle i need "id in (1,2,3,4,5)" 
then use genInValues(",", "", "", name);
But for Postgres i need "id in (values (1),(2),(3),(4),(5))"
then use genInValues(",", "(", ")", name);

How do I detect "shift+enter" and generate a new line in Textarea?

Better use simpler solution:

Tim's solution below is better I suggest using that: https://stackoverflow.com/a/6015906/4031815


My solution

I think you can do something like this..

EDIT : Changed the code to work irrespective of the caret postion

First part of the code is to get the caret position.

Ref: How to get the caret column (not pixels) position in a textarea, in characters, from the start?

function getCaret(el) { 
    if (el.selectionStart) { 
        return el.selectionStart; 
    } else if (document.selection) { 
        el.focus();
        var r = document.selection.createRange(); 
        if (r == null) { 
            return 0;
        }
        var re = el.createTextRange(), rc = re.duplicate();
        re.moveToBookmark(r.getBookmark());
        rc.setEndPoint('EndToStart', re);
        return rc.text.length;
    }  
    return 0; 
}

And then replacing the textarea value accordingly when Shift + Enter together , submit the form if Enter is pressed alone.

$('textarea').keyup(function (event) {
    if (event.keyCode == 13) {
        var content = this.value;  
        var caret = getCaret(this);          
        if(event.shiftKey){
            this.value = content.substring(0, caret - 1) + "\n" + content.substring(caret, content.length);
            event.stopPropagation();
        } else {
            this.value = content.substring(0, caret - 1) + content.substring(caret, content.length);
            $('form').submit();
        }
    }
});

Here is a demo

Forward host port to docker container

A simple but relatively insecure way would be to use the --net=host option to docker run.

This option makes it so that the container uses the networking stack of the host. Then you can connect to services running on the host simply by using "localhost" as the hostname.

This is easier to configure because you won't have to configure the service to accept connections from the IP address of your docker container, and you won't have to tell the docker container a specific IP address or host name to connect to, just a port.

For example, you can test it out by running the following command, which assumes your image is called my_image, your image includes the telnet utility, and the service you want to connect to is on port 25:

docker run --rm -i -t --net=host my_image telnet localhost 25

If you consider doing it this way, please see the caution about security on this page:

https://docs.docker.com/articles/networking/

It says:

--net=host -- Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick ip addr command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does not let the container reconfigure the host network stack — that would require --privileged=true — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like restart your computer. You should use this option with caution.

How can git be installed on CENTOS 5.5?

I've tried few methods from this question and they all failed on my CentOs, either because of the wrong repos or missing files.

Here is the method which works for me (when installing version 1.7.8):

    yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
    wget http://git-core.googlecode.com/files/git-1.7.8.tar.gz
    tar -xzvf ./git-1.7.8.tar.gz
    cd ./git-1.7.8
    ./configure
    make
    make install 

You may want to download a different version from here: http://code.google.com/p/git-core/downloads/list

How can I center an image in Bootstrap?

Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto. This can be done with built-in .d-block:

<div class="container">
    <div class="row">
        <div class="col-4">
            <img class="mx-auto d-block" src="...">  
        </div>
    </div>
</div>

Or leave it as inline-block and wrapped it in a div with .text-center:

<div class="container">
    <div class="row">
        <div class="col-4">
          <div class="text-center">
            <img src="..."> 
          </div>     
        </div>
    </div>
</div>

I made a fiddle showing both ways. They are documented here as well.

How to query a CLOB column in Oracle

This works

select DBMS_LOB.substr(myColumn, 3000) from myTable

Python pandas: fill a dataframe row by row

My approach was, but I can't guarantee that this is the fastest solution.

df = pd.DataFrame(columns=["firstname", "lastname"])
df = df.append({
     "firstname": "John",
     "lastname":  "Johny"
      }, ignore_index=True)

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio

  • IDE
  • Except for free editions, it is a paid IDE.
  • It is quite heavy on CPU and lags on lower end PCs.
  • It is mostly used for Windows software development including DirectX programs, Windows API, etc.
  • Advanced IntelliSense (best one ever; Visual Studio Code's IntelliSense extension takes second place)
  • It features built-in debuggers, easy-to-configure project settings (though developers tend to not use the GUI ones)
  • Microsoft support (more than Visual Studio Code)
  • Mostly used for C/C++ (Windows), .NET and C# projects along with SQL Server, database, etc.
  • Extreme large download size, space utilization and the slow downs over time.
    • It is the only con that forces me to use Visual Studio Code for smaller projects*
  • Includes tools to generate dependency graphs. Refactoring tools have great support for Visual Studio.
  • Has a VYSIWYG editor for VB.NET, C++.NET, and C#. (It is easy enough for first time users instead of getting through windows.h)

Visual Studio Code

  • Free open source text editor
  • Has IntelliSense (but it doesn't work out of box if Visual Studio is not installed, need to configure to point to MinGW, etc.)
  • Smaller download size and RAM requirements. With IntelliSense it requires around 300 MB RAM. (Edit : Some header files tend to blow up memory requirements to 7-8 GBs eg. OpenGL and GLM Libraries)
  • It works on lower-end PCs. (it is still slow to start up especially if PowerShell is used instead of CMD)
  • Lower support (open source, so you can modify it yourself)
  • Build tasks are project specific. Even if you want to build it in a vanilla configuration.
  • Mostly used for web development (this applies to all free text editors). They tend to show off JavaScript / HTML support over C/C++. Visual Studio shows off Visual Basic/C++ over other languages.
  • Lack of good extensions (it's still new though)
  • Gives you a hard time to reconfigure your project/workspace settings. I prefer the GUI way.
  • Cross platform
  • Has an integrated terminal (PowerShell is too slow at startup though)
  • It is best for smaller projects and test code (you know if you are bored and want to print "Hello, World!", it does not make sense to wait 3-5 minutes while Visual Studio loads up, and then another minute or 2 at project creation and then finally getting it to print "Hello, World!").

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

Accessing @attribute from SimpleXML

Try this

$xml->attributes()->Token

Can a PDF file's print dialog be opened with Javascript?

Why not use the Actions menu option to set this?

Do the following: If you have Acrobat Pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose 'Execute a menu item'. Click the Add button then select 'File > Print' then OK. Click OK again and save the PDF.

CSS text-transform capitalize on all caps

I know this is a late response but if you want to compare the performance of various solutions I have a jsPerf that I created.

Regex solutions are the fastest for sure.

Here is the jsPerf: https://jsperf.com/capitalize-jwaz

There are 2 regex solutions.

The first one uses/\b[a-z]/g. Word boundary will capital words such as non-disclosure to Non-Disclosure.

If you only want to capitalize letters that are preceded by a space then use the second regex

/(^[a-z]|\s[a-z])/g

Why can a function modify some arguments as perceived by the caller, but not others?

I had modified my answer tons of times and realized i don't have to say anything, python had explained itself already.

a = 'string'
a.replace('t', '_')
print(a)
>>> 'string'

a = a.replace('t', '_')
print(a)
>>> 's_ring'

b = 100
b + 1
print(b)
>>> 100

b = b + 1
print(b)
>>> 101

def test_id(arg):
    c = id(arg)
    arg = 123
    d = id(arg)
    return

a = 'test ids'
b = id(a)
test_id(a)
e = id(a)

# b = c  = e != d
# this function do change original value
del change_like_mutable(arg):
    arg.append(1)
    arg.insert(0, 9)
    arg.remove(2)
    return

test_1 = [1, 2, 3]
change_like_mutable(test_1)



# this function doesn't 
def wont_change_like_str(arg):
     arg = [1, 2, 3]
     return


test_2 = [1, 1, 1]
wont_change_like_str(test_2)
print("Doesn't change like a imutable", test_2)

This devil is not the reference / value / mutable or not / instance, name space or variable / list or str, IT IS THE SYNTAX, EQUAL SIGN.

PowerShell to remove text from a string

$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]

returns

keep this

Unable to begin a distributed transaction

My last adventure with MSDTC and this error today turned out to be a DNS issue. You're on the right track asking if the machines are on the same domain, EBarr. Terrific list for this issue, by the way!

My situation: I needed a server in a child domain to be able to run distributed transactions against a server in the parent domain through a firewall. I've used linked servers quite a bit over the years, so I had all the usual settings in SQL for a linked server and in MSDTC that Ian documented so nicely above. I set up MSDTC with a range of TCP ports (5000-5200) to use on both servers, and arranged for a firewall hole between the boxes for ports 1433 and 5000-5200. That should have worked. The linked server tested OK and I could query the remote SQL server via the linked server nicely, but I couldn't get it to allow a distributed transaction. I could even see a connection on the QA server from the DEV server, but something wasn't making the trip back.

I could PING the DEV server from QA using a FQDN like: PING DEVSQL.dev.domain.com

I could not PING the DEV server with just the machine name: PING DEVSQL

The DEVSQL server was supposed to be a member of both domains, but the name wasn't resolving in the parent domain's DNS... something had happened to the machine account for DEVSQL in the parent domain. Once we added DEVSQL to the DNS for the parent domain, and "PING DEVSQL" worked from the remote QA server, this issue was resolved for us.

I hope this helps!

Writing String to Stream and reading it back does not work

You need to reset the stream to the beginning:

stringAsStream.Seek(0, SeekOrigin.Begin);
Console.WriteLine("Differs from:\t" + (char)stringAsStream.ReadByte());

This can also be done by setting the Position property to 0:

stringAsStream.Position = 0

Permissions error when connecting to EC2 via SSH on Mac OSx

Had a similar issue. Here are the steps used to setup SSH keys and forwarding on the Mac. Made these notes for myself - may help someone... check against your config.

The assumption here is there are no keys setup. If you already have the keys setup skip this section.

$ ssh-keygen -t rsa -b 4096

Generating public/private rsa key pair.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter] Enter passphrase (empty for no passphrase): [Type a passphrase] Enter same passphrase again: [Type passphrase again]

Modify ~/.ssh/config adding the entry for the key file:

~/.ssh/config should look similar to:

Host *

AddKeysToAgent yes

UseKeychain yes

IdentityFile ~/.ssh/id_rsa

Store the private key in the keychain:

$ ssh-add -K ~/.ssh/id_rsa

Go test it now with: ssh -A username@yourhostname

Should forward your key to yourhostname. Assuming your keys are added on you should connect without issue.

Difference between arguments and parameters in Java

In java, there are two types of parameters, implicit parameters and explicit parameters. Explicit parameters are the arguments passed into a method. The implicit parameter of a method is the instance that the method is called from. Arguments are simply one of the two types of parameters.