Programs & Examples On #Subclass

A subclass is a class that derives or inherits from a parent (or super) class. Subclassing is used extensively in object-oriented programming (OOP).

What is a Subclass

It is a class that extends another class.

example taken from https://www.java-tips.org/java-se-tips-100019/24-java-lang/784-what-is-a-java-subclass.html, Cat is a sub class of Animal :-)

public class Animal {

    public static void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }
}

public class Cat extends Animal {

    public static void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();
    }
}

Class extending more than one class Java?

No it is not possible in java (Maybe in java 8 it will be avilable). Except the case when you extend in a tree. For example:

class A
class B extends A
class C extends B

How do you find all subclasses of a given class in Java?

I needed to do this as a test case, to see if new classes had been added to the code. This is what I did

final static File rootFolder = new File(SuperClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
private static ArrayList<String> files = new ArrayList<String>();
listFilesForFolder(rootFolder); 

@Test(timeout = 1000)
public void testNumberOfSubclasses(){
    ArrayList<String> listSubclasses = new ArrayList<>(files);
    listSubclasses.removeIf(s -> !s.contains("Superclass.class"));
    for(String subclass : listSubclasses){
        System.out.println(subclass);
    }
    assertTrue("You did not create a new subclass!", listSubclasses.size() >1);     
}

public static void listFilesForFolder(final File folder) {
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
        } else {
            files.add(fileEntry.getName().toString());
        }
    }
}

How do I check if an object's type is a particular subclass in C++?

You can only do it at compile time using templates, unless you use RTTI.

It lets you use the typeid function which will yield a pointer to a type_info structure which contains information about the type.

Read up on it at Wikipedia

How to check if a subclass is an instance of a class at runtime?

Maybe I'm missing something, but wouldn't this suffice:

if (view instanceof B) {
    // this view is an instance of B
}

How do I check (at runtime) if one class is a subclass of another?

You can use isinstance if you have an instance, or issubclass if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.

How to find all the subclasses of a class given its name?

Note: I see that someone (not @unutbu) changed the referenced answer so that it no longer uses vars()['Foo'] — so the primary point of my post no longer applies.

FWIW, here's what I meant about @unutbu's answer only working with locally defined classes — and that using eval() instead of vars() would make it work with any accessible class, not only those defined in the current scope.

For those who dislike using eval(), a way is also shown to avoid it.

First here's a concrete example demonstrating the potential problem with using vars():

class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass

# unutbu's approach
def all_subclasses(cls):
    return cls.__subclasses__() + [g for s in cls.__subclasses__()
                                       for g in all_subclasses(s)]

print(all_subclasses(vars()['Foo']))  # Fine because  Foo is in scope
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

def func():  # won't work because Foo class is not locally defined
    print(all_subclasses(vars()['Foo']))

try:
    func()  # not OK because Foo is not local to func()
except Exception as e:
    print('calling func() raised exception: {!r}'.format(e))
    # -> calling func() raised exception: KeyError('Foo',)

print(all_subclasses(eval('Foo')))  # OK
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

# using eval('xxx') instead of vars()['xxx']
def func2():
    print(all_subclasses(eval('Foo')))

func2()  # Works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

This could be improved by moving the eval('ClassName') down into the function defined, which makes using it easier without loss of the additional generality gained by using eval() which unlike vars() is not context-sensitive:

# easier to use version
def all_subclasses2(classname):
    direct_subclasses = eval(classname).__subclasses__()
    return direct_subclasses + [g for s in direct_subclasses
                                    for g in all_subclasses2(s.__name__)]

# pass 'xxx' instead of eval('xxx')
def func_ez():
    print(all_subclasses2('Foo'))  # simpler

func_ez()
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

Lastly, it's possible, and perhaps even important in some cases, to avoid using eval() for security reasons, so here's a version without it:

def get_all_subclasses(cls):
    """ Generator of all a class's subclasses. """
    try:
        for subclass in cls.__subclasses__():
            yield subclass
            for subclass in get_all_subclasses(subclass):
                yield subclass
    except TypeError:
        return

def all_subclasses3(classname):
    for cls in get_all_subclasses(object):  # object is base of all new-style classes.
        if cls.__name__.split('.')[-1] == classname:
            break
    else:
        raise ValueError('class %s not found' % classname)
    direct_subclasses = cls.__subclasses__()
    return direct_subclasses + [g for s in direct_subclasses
                                    for g in all_subclasses3(s.__name__)]

# no eval('xxx')
def func3():
    print(all_subclasses3('Foo'))

func3()  # Also works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

Delete a database in phpMyAdmin

  1. Connect to your localhost.
  2. Open your favorite browser.
  3. Make sure your localhost is working.
  4. Type in url= localhost.
  5. Scroll down click on phpadmin once phpadmin is open.
  6. Click on database.
  7. Mark check the database you want remove.
  8. Click on drop.

If this don't work

  1. Click on database go to operation
  2. Click drop database

Implement Validation for WPF TextBoxes

When I needed to do this, I followed Microsoft's example using Binding.ValidationRules and it worked first time.

See their article, How to: Implement Binding Validation: https://docs.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-binding-validation?view=netframeworkdesktop-4.8

How to install OpenJDK 11 on Windows?

From the comment by @ZhekaKozlov: ojdkbuild has OpenJDK builds (currently 8 and 11) for Windows (zip and msi).

How do you make an element "flash" in jQuery

After 5 years... (And no additional plugin needed)

This one "pulses" it to the color you want (e.g. white) by putting a div background color behind it, and then fading the object out and in again.

HTML object (e.g. button):

<div style="background: #fff;">
  <input type="submit" class="element" value="Whatever" />
</div>

jQuery (vanilla, no other plugins):

$('.element').fadeTo(100, 0.3, function() { $(this).fadeTo(500, 1.0); });

element - class name

first number in fadeTo() - milliseconds for the transition

second number in fadeTo() - opacity of the object after fade/unfade

You may check this out in the lower right corner of this webpage: https://single.majlovesreg.one/v1/

Edit (willsteel) no duplicated selector by using $(this) and tweaked values to acutally perform a flash (as the OP requested).

IIS Express gives Access Denied error when debugging ASP.NET MVC

I just fixed this exact problem in IIS EXPRESS fixed it by editing the application host .config to the location section specific to the below. I had set Windows Authentication in Visual Studio 2012 but when I went into the XML it looked like this.

the windows auth tag needed to be added below as shown.

<windowsAuthentication enabled="true" />

<location path="MyApplicationbeingDebugged">
        ``<system.webServer>
            <security>
                <authentication>
                    <anonymousAuthentication enabled="false" />
                    <!-- INSERT TAG HERE --> 
                </authentication>
            </security>
        </system.webServer>
</location>

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

Is there a way to detect if an image is blurry?

One way which I'm currently using measures the spread of edges in the image. Look for this paper:

@ARTICLE{Marziliano04perceptualblur,
    author = {Pina Marziliano and Frederic Dufaux and Stefan Winkler and Touradj Ebrahimi},
    title = {Perceptual blur and ringing metrics: Application to JPEG2000,” Signal Process},
    journal = {Image Commun},
    year = {2004},
    pages = {163--172} }

It's usually behind a paywall but I've seen some free copies around. Basically, they locate vertical edges in an image, and then measure how wide those edges are. Averaging the width gives the final blur estimation result for the image. Wider edges correspond to blurry images, and vice versa.

This problem belongs to the field of no-reference image quality estimation. If you look it up on Google Scholar, you'll get plenty of useful references.

EDIT

Here's a plot of the blur estimates obtained for the 5 images in nikie's post. Higher values correspond to greater blur. I used a fixed-size 11x11 Gaussian filter and varied the standard deviation (using imagemagick's convert command to obtain the blurred images).

enter image description here

If you compare images of different sizes, don't forget to normalize by the image width, since larger images will have wider edges.

Finally, a significant problem is distinguishing between artistic blur and undesired blur (caused by focus miss, compression, relative motion of the subject to the camera), but that is beyond simple approaches like this one. For an example of artistic blur, have a look at the Lenna image: Lenna's reflection in the mirror is blurry, but her face is perfectly in focus. This contributes to a higher blur estimate for the Lenna image.

Get protocol, domain, and port from URL

first get the current address

var url = window.location.href

Then just parse that string

var arr = url.split("/");

your url is:

var result = arr[0] + "//" + arr[2]

Hope this helps

Ajax using https on an http page

http://example.com/ may resolve to a different VirtualHost than https://example.com/ (which, as the Host header is not sent, responds to the default for that IP), so the two are treated as separate domains and thus subject to crossdomain JS restrictions.

JSON callbacks may let you avoid this.

How do I update the GUI from another thread?

Fire and forget extension method for .NET 3.5+

using System;
using System.Windows.Forms;

public static class ControlExtensions
{
    /// <summary>
    /// Executes the Action asynchronously on the UI thread, does not block execution on the calling thread.
    /// </summary>
    /// <param name="control"></param>
    /// <param name="code"></param>
    public static void UIThread(this Control @this, Action code)
    {
        if (@this.InvokeRequired)
        {
            @this.BeginInvoke(code);
        }
        else
        {
            code.Invoke();
        }
    }
}

This can be called using the following line of code:

this.UIThread(() => this.myLabel.Text = "Text Goes Here");

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Custom Drawable for ProgressBar/ProgressDialog

Custom progress with scale!

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_on"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_on"
            android:scaleGravity="center" />
    </item>

</animation-list>

TypeScript for ... of with index / key?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries

for (var [key, item] of someArray.entries()) { ... }

In TS this requires targeting ES2015 since it requires the runtime to support iterators, which ES5 runtimes don't. You can of course use something like Babel to make the output work on ES5 runtimes.

Now() function with time trim

Paste this function in your Module and use it as like formula

Public Function format_date(t As String)
    format_date = Format(t, "YYYY-MM-DD")
End Function

for example in Cell A1 apply this formula

=format_date(now())

it will return in YYYY-MM-DD format. Change any format (year month date) as your wish.

Twitter Bootstrap - how to center elements horizontally or vertically

i use this

<style>
    html, body {
        height: 100%;
        margin: 0;
        padding: 0 0;
    }

    .container-fluid {
        height: 100%;
        display: table;
        width: 100%;
        padding-right: 0;
        padding-left: 0;
    }

    .row-fluid {
        height: 100%;
        display: table-cell;
        vertical-align: middle;
        width: 100%;
    }

    .centering {
        float: none;
        margin: 0 auto;
    }
</style>
<body>
    <div class="container-fluid">
        <div class="row-fluid">
            <div class="offset3 span6 centering">
                content here
            </div>
        </div>
    </div>
</body>

How do I create variable variables?

It's not a good idea. If you are accessing a global variable you can use globals().

>>> a = 10
>>> globals()['a']
10

If you want to access a variable in the local scope you can use locals(), but you cannot assign values to the returned dict.

A better solution is to use getattr or store your variables in a dictionary and then access them by name.

Nested ifelse statement

Sorry for joining too late to the party. Here's an easy solution.

#building up your initial table
idnat <- c(1,1,1,2) #1 is french, 2 is foreign

idbp <- c(1,2,3,4) #1 is mainland, 2 is colony, 3 is overseas, 4 is foreign

t <- cbind(idnat, idbp)

#the last column will be a vector of row length = row length of your matrix
idnat2 <- vector()

#.. and we will populate that vector with a cursor

for(i in 1:length(idnat))

     #*check that we selected the cursor to for the length of one of the vectors*

{  

  if (t[i,1] == 2) #*this says: if idnat = foreign, then it's foreign*

    {

      idnat2[i] <- 3 #3 is foreign

    }

  else if (t[i,2] == 1) #*this says: if not foreign and idbp = mainland then it's mainland*

    {

      idnat2[i] <- 2 # 2 is mainland  

    }

  else #*this says: anything else will be classified as colony or overseas*

    {

      idnat2[i] <- 1 # 1 is colony or overseas 

    }

}


cbind(t,idnat2)

How do I copy the contents of one stream to another?

There is actually, a less heavy-handed way of doing a stream copy. Take note however, that this implies that you can store the entire file in memory. Don't try and use this if you are working with files that go into the hundreds of megabytes or more, without caution.

public static void CopySmallTextStream(Stream input, Stream output)
{
  using (StreamReader reader = new StreamReader(input))
  using (StreamWriter writer = new StreamWriter(output))
  {
    writer.Write(reader.ReadToEnd());
  }
}

NOTE: There may also be some issues concerning binary data and character encodings.

How to convert array values to lowercase in PHP?

`$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');

$strtolower = array_map('strtolower', $Color);

$strtoupper = array_map('strtoupper', $Color);

print_r($strtolower); print_r($strtoupper);`

HTML anchor link - href and onclick both?

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
  //code
  return true;
}

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

When to use React setState callback

this.setState({
    name:'value' 
},() => {
    console.log(this.state.name);
});

How to POST raw whole JSON in the body of a Retrofit request?

use following to send json

final JSONObject jsonBody = new JSONObject();
    try {

        jsonBody.put("key", "value");

    } catch (JSONException e){
        e.printStackTrace();
    }
    RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),(jsonBody).toString());

and pass it to url

@Body RequestBody key

How to check for empty value in Javascript?

Your script seems incorrect in several places.

Try this

var timetemp = document.getElementsByTagName('input');

for (var i = 0; i < timetemp.length; i++){
    if (timetemp[i].value == ""){
        alert ('No value');
    }
    else{
        alert (timetemp[i].value);
    }
}

Example: http://jsfiddle.net/jasongennaro/FSzT2/

Here's what I changed:

  1. started by getting all the inputs via TagName. This makes an array
  2. initialized i with a var and then looped through the timetemp array using the timetemp.length property.
  3. used timetemp[i] to reference each input in the for statement

Delaying AngularJS route change until model loaded to prevent flicker

This commit, which is part of version 1.1.5 and above, exposes the $promise object of $resource. Versions of ngResource including this commit allow resolving resources like this:

$routeProvider

resolve: {
    data: function(Resource) {
        return Resource.get().$promise;
    }
}

controller

app.controller('ResourceCtrl', ['$scope', 'data', function($scope, data) {

    $scope.data = data;

}]);

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

In Node.js, I wrote the following code which works but it is not based on selenium's official WebDriverJS, but based on SauceLabs's WebDriver: WD.js and a very compact image library called EasyImage.

I just wanna emphasize that you cannot really take the screenshot of an element but what you should do is to first, take the screenshot of the whole page, then select the part of the page you like and crop that specific part:

browser.get(URL_TO_VISIT)
       .waitForElementById(dependentElementId, webdriver.asserters.isDisplayed, 3000)
       .elementById(elementID)
        .getSize().then(function(size) {
            browser.elementById(elementID)
                   .getLocation().then(function(location) {
                        browser.takeScreenshot().then(function(data) {
                            var base64Data = data.replace(/^data:image\/png;base64,/, "");
                            fs.writeFile(filePath, base64Data, 'base64', function(err) {
                                if (err) {
                                    console.log(err);
                                } 
                                else {
                                    cropInFile(size, location, filePath);
                                }
                                doneCallback();
                        });
                    });
                });
            }); 

And the cropInFileFunction, goes like this:

var cropInFile = function(size, location, srcFile) {
    easyimg.crop({
            src: srcFile,
            dst: srcFile,
            cropwidth: size.width,
            cropheight: size.height,
            x: location.x,
            y: location.y,
            gravity: 'North-West'
        },
        function(err, stdout, stderr) {
            if (err) throw err;
        });
};

Find MongoDB records where array field is not empty

This also works:

db.getCollection('collectionName').find({'arrayName': {$elemMatch:{}}})

How to get value of a div using javascript

Value is not a valid attribute of DIV

try this

var divElement = document.getElementById('demo');
alert( divElement .getAttribute('value'));

Dead simple example of using Multiprocessing Queue, Pool and Locking

This might be not 100% related to the question, but on my search for an example of using multiprocessing with a queue this shows up first on google.

This is a basic example class that you can instantiate and put items in a queue and can wait until queue is finished. That's all I needed.

from multiprocessing import JoinableQueue
from multiprocessing.context import Process


class Renderer:
    queue = None

    def __init__(self, nb_workers=2):
        self.queue = JoinableQueue()
        self.processes = [Process(target=self.upload) for i in range(nb_workers)]
        for p in self.processes:
            p.start()

    def render(self, item):
        self.queue.put(item)

    def upload(self):
        while True:
            item = self.queue.get()
            if item is None:
                break

            # process your item here

            self.queue.task_done()

    def terminate(self):
        """ wait until queue is empty and terminate processes """
        self.queue.join()
        for p in self.processes:
            p.terminate()

r = Renderer()
r.render(item1)
r.render(item2)
r.terminate()

exception in initializer error in java when using Netbeans

Wherever there is errors or exceptions in static blocks, this exception will be thrown. To get the cause of this exception simply use Throwable.getCause() to know what is wrong.

How to count rows with SELECT COUNT(*) with SQLAlchemy?

If you are using the SQL Expression Style approach there is another way to construct the count statement if you already have your table object.

Preparations to get the table object. There are also different ways.

import sqlalchemy

database_engine = sqlalchemy.create_engine("connection string")

# Populate existing database via reflection into sqlalchemy objects
database_metadata = sqlalchemy.MetaData()
database_metadata.reflect(bind=database_engine)

table_object = database_metadata.tables.get("table_name") # This is just for illustration how to get the table_object                    

Issuing the count query on the table_object

query = table_object.count()
# This will produce something like, where id is a primary key column in "table_name" automatically selected by sqlalchemy
# 'SELECT count(table_name.id) AS tbl_row_count FROM table_name'

count_result = database_engine.scalar(query)

How to setup FTP on xampp

XAMPP for linux and mac comes with ProFTPD. Make sure to start the service from XAMPP control panel -> manage servers.

Further complete instructions can be found at localhost XAMPP dashboard -> How-to guides -> Configure FTP Access. I have pasted them below :

  1. Open a new Linux terminal and ensure you are logged in as root.

  2. Create a new group named ftp. This group will contain those user accounts allowed to upload files via FTP.

groupadd ftp

  1. Add your account (in this example, susan) to the new group. Add other users if needed.

usermod -a -G ftp susan

  1. Change the ownership and permissions of the htdocs/ subdirectory of the XAMPP installation directory (typically, /opt/lampp) so that it is writable by the the new ftp group.

cd /opt/lampp chown root.ftp htdocs chmod 775 htdocs

  1. Ensure that proFTPD is running in the XAMPP control panel.

You can now transfer files to the XAMPP server using the steps below:

  1. Start an FTP client like winSCP or FileZilla and enter connection details as below.

If you’re connecting to the server from the same system, use "127.0.0.1" as the host address. If you’re connecting from a different system, use the network hostname or IP address of the XAMPP server.

Use "21" as the port.

Enter your Linux username and password as your FTP credentials.

Your FTP client should now connect to the server and enter the /opt/lampp/htdocs/ directory, which is the default Web server document root.

  1. Transfer the file from your home directory to the server using normal FTP transfer conventions. If you’re using a graphical FTP client, you can usually drag and drop the file from one directory to the other. If you’re using a command-line FTP client, you can use the FTP PUT command.

Once the file is successfully transferred, you should be able to see it in action.

Python list iterator behavior and next(iterator)

What is happening is that next(a) returns the next value of a, which is printed to the console because it is not affected.

What you can do is affect a variable with this value:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    b=next(a)
...
0
2
4
6
8

Binary Data in JSON String. Something better than Base64

While it is true that base64 has ~33% expansion rate, it is not necessarily true that processing overhead is significantly more than this: it really depends on JSON library/toolkit you are using. Encoding and decoding are simple straight-forward operations, and they can even be optimized wrt character encoding (as JSON only supports UTF-8/16/32) -- base64 characters are always single-byte for JSON String entries. For example on Java platform there are libraries that can do the job rather efficiently, so that overhead is mostly due to expanded size.

I agree with two earlier answers:

  • base64 is simple, commonly used standard, so it is unlikely to find something better specifically to use with JSON (base-85 is used by postscript etc; but benefits are at best marginal when you think about it)
  • compression before encoding (and after decoding) may make lots of sense, depending on data you use

AppCompat v7 r21 returning error in values.xml?

changing the complie SDk version to API level 21 fixed it for me. then i ran into others issues of deploying the app to my device. i changed the minimun API level to target to what i want and that fixed it.

incase someone is experiencing this again.

how to kill hadoop jobs

Use below command to kill all jobs running on yarn.

For accepted jobs use below command.

for x in $(yarn application -list -appStates ACCEPTED | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done

For running, jobs use the below command.

for x in $(yarn application -list -appStates RUNNING | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

How to set the Default Page in ASP.NET?

I had done all the above solutions but it did not work.

My default page wasn't an aspx page, it was an html page.

This article solved the problem. https://weblog.west-wind.com/posts/2013/aug/15/iis-default-documents-vs-aspnet-mvc-routes

Basically, in my \App_Start\RouteConfig.cs file, I had to add a line:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("");   // This was the line I had to add here!

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

Hope this helps someone, it took me a goodly while to find the answer.

Highlighting Text Color using Html.fromHtml() in Android?

font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")

Connecting an input stream to an outputstream

Just because you use a buffer doesn't mean the stream has to fill that buffer. In other words, this should be okay:

public static void copyStream(InputStream input, OutputStream output)
    throws IOException
{
    byte[] buffer = new byte[1024]; // Adjust if you want
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
}

That should work fine - basically the read call will block until there's some data available, but it won't wait until it's all available to fill the buffer. (I suppose it could, and I believe FileInputStream usually will fill the buffer, but a stream attached to a socket is more likely to give you the data immediately.)

I think it's worth at least trying this simple solution first.

PHP create key => value pairs within a foreach

function createOfferUrlArray($Offer) {
    $offerArray = array();
    foreach ($Offer as $key => $value) { 
        $offerArray[$key] = $value[4];
    }
    return $offerArray;
}

or

function createOfferUrlArray($offer) {
    foreach ( $offer as &$value ) {
        $value = $value[4];
    }
    unset($value);
    return $offer;
}

Determining the current foreground application from a background task or service

In lollipop and up:

Add to mainfest:

<uses-permission android:name="android.permission.GET_TASKS" />

And do something like this:

if( mTaskId < 0 )
{
    List<AppTask> tasks = mActivityManager.getAppTasks(); 
    if( tasks.size() > 0 )
        mTaskId = tasks.get( 0 ).getTaskInfo().id;
}

github: server certificate verification failed

I also was having this error when trying to clone a repository from Github on a Windows Subsystem from Linux console:

fatal: unable to access 'http://github.com/docker/getting-started.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

The solution from @VonC on this thread didn't work for me.

The solution from this Fabian Lee's article solved it for me:

openssl s_client -showcerts -servername github.com -connect github.com:443 </dev/null 2>/dev/null | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p'  > github-com.pem
cat github-com.pem | sudo tee -a /etc/ssl/certs/ca-certificates.crt

How to return a list of keys from a Hash Map?

map.keySet()

will return you all the keys. If you want the keys to be sorted, you might consider a TreeMap

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

If you're not too bothered about the width of the padding, this solution will actually keep the padding in percentages too..

textarea
{
    border:1px solid #999999;
    width:98%;
    margin:5px 0;
    padding:1%;
}

Not perfect, but you'll get some padding and the width adds up to 100% so its all good

100% width table overflowing div container

Add display: block; and overflow: auto; to .my-table. This will simply cut off anything past the 280px limit you enforced. There's no way to make it "look pretty" with that requirement due to words like pélagosthrough which are wider than 280px.

Centering FontAwesome icons vertically and horizontally

I just lowered the height to 28px on the .login-icon [class*='icon-'] Here's the fiddle: http://jsfiddle.net/mZHg7/

.login-icon [class*='icon-']{
    height: 28px;
    width: 50px;
    display: inline-block;
    text-align: center;
    vertical-align: baseline;
}

Run an Ansible task only when the variable contains a specific string

From Ansible 2.5

when: variable1 is search("value")

.war vs .ear file

war - web archive. It is used to deploy web applications according to the servlet standard. It is a jar file containing a special directory called WEB-INF and several files and directories inside it (web.xml, lib, classes) as well as all the HTML, JSP, images, CSS, JavaScript and other resources of the web application

ear - enterprise archive. It is used to deploy enterprise application containing EJBs, web applications, and 3rd party libraries. It is also a jar file, it has a special directory called APP-INF that contains the application.xml file, and it contains jar and war files.

Css Move element from left to right animated

You should try doing it with css3 animation. Check the code bellow:

<!DOCTYPE html>
<html>
<head>
<style> 
div {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation: myfirst 5s infinite; /* Chrome, Safari, Opera */
    -webkit-animation-direction: alternate; /* Chrome, Safari, Opera */
    animation: myfirst 5s infinite;
    animation-direction: alternate;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}

@keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}
</style>
</head>
<body>

<p><strong>Note:</strong> The animation-direction property is not supported in Internet Explorer 9 and earlier versions.</p>
<div></div>

</body>
</html>

Where 'div' is your animated object.

I hope you find this useful.

Thanks.

Why do we use volatile keyword?

In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia

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

How do I find out which DOM element has the focus?

There are potential problems with using document.activeElement. Consider:

<div contentEditable="true">
  <div>Some text</div>
  <div>Some text</div>
  <div>Some text</div>
</div>

If the user focuses on an inner-div, then document.activeElement still references the outer div. You cannot use document.activeElement to determine which of the inner div's has focus.

The following function gets around this, and returns the focused node:

function active_node(){
  return window.getSelection().anchorNode;
}

If you would rather get the focused element, use:

function active_element(){
  var anchor = window.getSelection().anchorNode;
  if(anchor.nodeType == 3){
        return anchor.parentNode;
  }else if(anchor.nodeType == 1){
        return anchor;
  }
}

Assign output of os.system to a variable and prevent it from being displayed on the screen

The commands module is a reasonably high-level way to do this:

import commands
status, output = commands.getstatusoutput("cat /etc/services")

status is 0, output is the contents of /etc/services.

Referring to a Column Alias in a WHERE Clause

You could refer to column alias but you need to define it using CROSS/OUTER APPLY:

SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;

DBFiddle Demo

Pros:

  • single definition of expression(easier to maintain/no need of copying-paste)
  • no need for wrapping entire query with CTE/outerquery
  • possibility to refer in WHERE/GROUP BY/ORDER BY
  • possible better performance(single execution)

Python code to remove HTML tags from a string

Python has several XML modules built in. The simplest one for the case that you already have a string with the full HTML is xml.etree, which works (somewhat) similarly to the lxml example you mention:

def remove_tags(text):
    return ''.join(xml.etree.ElementTree.fromstring(text).itertext())

Android Studio Gradle Already disposed Module

below solution works for me

  1. Delete all .iml files
  2. Rebuild project

SQL exclude a column using SELECT * [except columnA] FROM tableA?

Is there a way to exclude column(s) from a table without specifying all the columns?

Using declarative SQL in the usual way, no.

I think your proposed syntax is worthy and good. In fact, the relational database language 'Tutorial D' has a very similar syntax where the keywords ALL BUT are followed by a set of attributes (columns).

However, SQL's SELECT * already gets a lot a flak (@Guffa's answer here is a typical objection), so I don't think SELECT ALL BUT will get into the SQL Standard anytime soon.

I think the best 'work around' is to create a VIEW with only the columns you desire then SELECT * FROM ThatView.

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

You are not creating datetime index properly,

format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))

How to get a responsive button in bootstrap 3

<a href="#"><button type="button" class="btn btn-info btn-block regular-link"> <span class="text">Create New Board</span></button></a>

We can use btn-block for automatic responsive.

Find JavaScript function definition in Chrome

In Google chrome, Inspect element tool you can view any Javascript function definition.

  1. Click on the Sources tab. Then select the index page. Search for the function.

enter image description here

  1. Select the function then Right-click on the function and select "Evaluate selected text in console."

enter image description here

Laravel migration default value

Put the default value in single quote and it will work as intended. An example of migration:

$table->increments('id');
            $table->string('name');
            $table->string('url');
            $table->string('country');
            $table->tinyInteger('status')->default('1');
            $table->timestamps();

EDIT : in your case ->default('100.0');

get parent's view from a layout

If you are trying to find a View from your Fragment then try doing it like this:

int w = ((EditText)getActivity().findViewById(R.id.editText1)).getLayoutParams().width;

Syntax for a for loop in ruby

limit = array.length;
for counter in 0..limit
 --- make some actions ---
end

the other way to do that is the following

3.times do |n|
  puts n;
end

thats will print 0, 1, 2, so could be used like array iterator also

Think that variant better fit to the author's needs

Footnotes for tables in LaTeX

The best way to do it without any headache is to use the \tablefootnote command from the tablefootnote package. Add the following to your preamble:

\usepackage{tablefootnote}

It just works without the need of additional tricks.

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

In Python 3.9

Based on PEP 584, the new version of Python introduces two new operators for dictionaries: union (|) and in-place union (|=). You can use | to merge two dictionaries, while |= will update a dictionary in place:

>>> pycon = {2016: "Portland", 2018: "Cleveland"}
>>> europython = {2017: "Rimini", 2018: "Edinburgh", 2019: "Basel"}

>>> pycon | europython
{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}

>>> pycon |= europython
>>> pycon
{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}

If d1 and d2 are two dictionaries, then d1 | d2 does the same as {**d1, **d2}. The | operator is used for calculating the union of sets, so the notation may already be familiar to you.

One advantage of using | is that it works on different dictionary-like types and keeps the type through the merge:

>>> from collections import defaultdict
>>> europe = defaultdict(lambda: "", {"Norway": "Oslo", "Spain": "Madrid"})
>>> africa = defaultdict(lambda: "", {"Egypt": "Cairo", "Zimbabwe": "Harare"})

>>> europe | africa
defaultdict(<function <lambda> at 0x7f0cb42a6700>,
  {'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'})

>>> {**europe, **africa}
{'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'}

You can use a defaultdict when you want to effectively handle missing keys. Note that | preserves the defaultdict, while {**europe, **africa} does not.

There are some similarities between how | works for dictionaries and how + works for lists. In fact, the + operator was originally proposed to merge dictionaries as well. This correspondence becomes even more evident when you look at the in-place operator.

The basic use of |= is to update a dictionary in place, similar to .update():

>>> libraries = {
...     "collections": "Container datatypes",
...     "math": "Mathematical functions",
... }
>>> libraries |= {"zoneinfo": "IANA time zone support"}
>>> libraries
{'collections': 'Container datatypes', 'math': 'Mathematical functions',
 'zoneinfo': 'IANA time zone support'}

When you merge dictionaries with |, both dictionaries need to be of a proper dictionary type. On the other hand, the in-place operator (|=) is happy to work with any dictionary-like data structure:

>>> libraries |= [("graphlib", "Functionality for graph-like structures")]
>>> libraries
{'collections': 'Container datatypes', 'math': 'Mathematical functions',
 'zoneinfo': 'IANA time zone support',
 'graphlib': 'Functionality for graph-like structures'}

How to round the double value to 2 decimal points?

There's no difference in internal representation between 2 and 2.00. You can use Math.round to round a value to the nearest integer - to make that round to 2 decimal places you could multiply by 100, round, and then divide by 100, but you shouldn't expect the result to be exactly 2dps, due to the nature of binary floating point arithmetic.

If you're only interested in formatting a value to two decimal places, look at DecimalFormat - if you're interested in a number of decimal places while calculating you should really be using BigDecimal. That way you'll know that you really are dealing with decimal digits, rather than "the nearest available double value".

Another option you may want to consider if you're always dealing with two decimal places is to store the value as a long or BigInteger, knowing that it's exactly 100 times the "real" value - effectively storing cents instead of dollars, for example.

Uri not Absolute exception getting while calling Restful Webservice

For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: @Value annotation.

Django gives Bad Request (400) when DEBUG = False

The ALLOWED_HOSTS list should contain fully qualified host names, not urls. Leave out the port and the protocol. If you are using 127.0.0.1, I would add localhost to the list too:

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

You could also use * to match any host:

ALLOWED_HOSTS = ['*']

Quoting the documentation:

Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE_CLASSES).

Bold emphasis mine.

The status 400 response you get is due to a SuspiciousOperation exception being raised when your host header doesn't match any values in that list.

How can I send an Ajax Request on button click from a form with 2 buttons?

Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.

$("#button_1, #button_2").on("click", function(e) {
    e.preventDefault();
    $.ajax({type: "POST",
        url: "/pages/test/",
        data: { id: $(this).val(), access_token: $("#access_token").val() },
        success:function(result) {
          alert('ok');
        },
        error:function(result) {
          alert('error');
        }
    });
});

PHP mkdir: Permission denied problem

After you install the ftp server with sudo apt-get install vsftpd you will have to configure it. To enable write access you have to edit the /etc/vsftpd.conf file and uncomment the

#write_enable=YES

line, so it should read

write_enable=YES

Save the file and restart vsftpd with sudo service vsftpd restart.

For other configuration options consult this documentation or man vsftpd.conf

how to check if input field is empty

As javascript is dynamically typed, rather than using the .length property as above you can simply treat the input value as a boolean:

var input = $.trim($("#spa").val());

if (input) {
    // Do Stuff
}

You can also extract the logic out into functions, then by assigning a class and using the each() method the code is more dynamic if, for example, in the future you wanted to add another input you wouldn't need to change any code.

So rather than hard coding the function call into the input markup, you can give the inputs a class, in this example it's test, and use:

$(".test").each(function () {
    $(this).keyup(function () {
        $("#submit").prop("disabled", CheckInputs());
    });
});

which would then call the following and return a boolean value to assign to the disabled property:

function CheckInputs() {
    var valid = false;
    $(".test").each(function () {
        if (valid) { return valid; }
        valid = !$.trim($(this).val());
    });
    return valid;
}

You can see a working example of everything I've mentioned in this JSFiddle.

Replacing .NET WebBrowser control with a better browser, like Chrome?

UPDATE 2020 JULY

Preview version of chromium based WebView 2 is released by the Microsoft. Now you can embed new Chromium Edge browser into a .NET application.

UPDATE 2018 MAY

If you're targeting application to run on Windows 10, then now you can embed Edge browser into your .NET application by using Windows Community Toolkit.

WPF Example:

  1. Install Windows Community Toolkit Nuget Package

    Install-Package Microsoft.Toolkit.Win32.UI.Controls
    
  2. XAML Code

    <Window
        x:Class="WebViewTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:WPF="clr-namespace:Microsoft.Toolkit.Win32.UI.Controls.WPF;assembly=Microsoft.Toolkit.Win32.UI.Controls"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WebViewTest"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="MainWindow"
        Width="800"
        Height="450"
        mc:Ignorable="d">
        <Grid>
            <WPF:WebView x:Name="wvc" />
        </Grid>
    </Window>
    
  3. CS Code:

    public partial class MainWindow : Window
    {
      public MainWindow()
      {
        InitializeComponent();
    
        // You can also use the Source property here or in the WPF designer
        wvc.Navigate(new Uri("https://www.microsoft.com"));
      }
    }
    

WinForms Example:

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();

    // You can also use the Source property here or in the designer
    webView1.Navigate(new Uri("https://www.microsoft.com"));
  }
}

Please refer to this link for more information.

Adding space/padding to a UILabel

I edited a little in the accepted answer. There is a problem when leftInset and rightInset increase, a part of text will be disappeared, b/c the width of label will be narrowed but the height does not increase as figure:

padding label with wrong intrinsic content size

To resolve this problem you need to re-calculate height of text as follow:

@IBDesignable class PaddingLabel: UILabel {

  @IBInspectable var topInset: CGFloat = 20.0
  @IBInspectable var bottomInset: CGFloat = 20.0
  @IBInspectable var leftInset: CGFloat = 20.0
  @IBInspectable var rightInset: CGFloat = 20.0

  override func drawTextInRect(rect: CGRect) {
    let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
    super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
  }

  override func intrinsicContentSize() -> CGSize {
    var intrinsicSuperViewContentSize = super.intrinsicContentSize()

    let textWidth = frame.size.width - (self.leftInset + self.rightInset)
    let newSize = self.text!.boundingRectWithSize(CGSizeMake(textWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
    intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset

    return intrinsicSuperViewContentSize
  }
}

and result:

padding label with right intrinsic content size

I hope to help some people in the same situation as me.

Add swipe to delete UITableViewCell

@available(iOS 11.0, *)
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

        let editAction = UIContextualAction.init(style: UIContextualAction.Style.normal, title: "Edit", handler: { (action, view, completion) in
            //TODO: Edit
            completion(true)
            self.popUpViewPresent(index:indexPath.row)
        })

        let deleteAction = UIContextualAction.init(style: UIContextualAction.Style.destructive, title: "Delete", handler: { (action, view, completion) in
            //TODO: Delete
            completion(true)
            self.deleteTagAction(senderTag:indexPath.row)
        })
        editAction.image = UIImage(named: "Edit-white")
        deleteAction.image = UIImage(named: "Delete-white")
        editAction.backgroundColor = UIColor.gray
        deleteAction.backgroundColor = UIColor.red

        let config = UISwipeActionsConfiguration(actions: [deleteAction, editAction])
        config.performsFirstActionWithFullSwipe = false
        return config
    }

A better way to check if a path exists or not in PowerShell

To check if a Path exists to a directory, use this one:

$pathToDirectory = "c:\program files\blahblah\"
if (![System.IO.Directory]::Exists($pathToDirectory))
{
 mkdir $path1
}

To check if a Path to a file exists use what @Mathias suggested:

[System.IO.File]::Exists($pathToAFile)

Delete last char of string

Strings in c# are immutable. When in your code you do strgroupids.TrimEnd(','); or strgroupids.TrimEnd(new char[] { ',' }); the strgroupids string is not modified.

You need to do something like strgroupids = strgroupids.TrimEnd(','); instead.

To quote from here:

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

Command-line Unix ASCII-based charting / plotting tool

See also: asciichart (implemented in Node.js, Python, Java, Go and Haskell)

enter image description here

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

ToggleButton in C# WinForms

You may also consider the ToolStripButton control if you don't mind hosting it in a ToolStripContainer. I think it can natively support pressed and unpressed states.

Maven: repository element was not specified in the POM inside distributionManagement?

The ID of the two repos are both localSnap; that's probably not what you want and it might confuse Maven.

If that's not it: There might be more repository elements in your POM. Search the output of mvn help:effective-pom for repository to make sure the number and place of them is what you expect.

how to call a method in another Activity from Activity

Declare a SecondActivity variable in FirstActivity

Like this

public class FirstActivity extends Activity {  

SecondActivity secactivity;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);
  }      

  public void method() {
    // some code

  secactivity.call_method();// 'Method' is Name of the any one method in SecondActivity

  }  
}  

Using this format you can call any method from one activity to another.

src absolute path problem

You should be referencing it as localhost. Like this:

<img src="http:\\localhost\site\img\mypicture.jpg"/>

Get Request and Session Parameters and Attributes from JSF pages

You can also use a bean (request scoped is suggested) and directly access the context by way of the FacesContext.

You can get the HttpServletRequest and HttpServletResposne objects by using the following code:

HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse res = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();

After this, you can access individual parameters via getParameter(paramName) or access the full map via getParameterMap() req object

The reason I suggest a request scoped bean is that you can use these during initialization (worst case scenario being the constructor. Most frameworks give you some place to do code at bean initialization time) and they will be done as your request comes in.

It is, however, a bit of a hack. ;) You may want to look into seeing if there is a JSF Acegi module that will allow you to get access to the variables you need.

Where is the Docker daemon log?

For Docker Mac Native (without Boot2Docker or docker-machine, running your Docker installation without extra VirtualBox - which I would recommend over the others), all the answers didn´t work for me. But the Docker docs fortunately came to the rescue.

If you want to see the docker daemon logs on commandline, just type:

syslog -k Sender Docker

Alternatively from Mac OS Sierra on, you can use the newly designed Mac Console App (don´t get confused here with the App "Terminal", the Console App´s icon looks quite similar - I found it with the Launchpad below "Others.."). There´s an article here which describes the general usage of the new Mac OS Sierra Console App, which didn´t make it into the official Docker docs yet.

Inside the Console App just choose system.log and type Docker into the search bar. That´s it. Now you should see all Docker related logs.

Reading Data From Database and storing in Array List object

Instead ofnull, use CustomerDTO customers =new CustomerDTO()`;

CustomerDTO customer = null;


  private static List<Author> getAllAuthors() {
    initConnection();
    List<Author> authors = new ArrayList<Author>();
    Author author = new Author();
    try {
        stmt = (Statement) conn.createStatement();
        String str = "SELECT * FROM author";
        rs = (ResultSet) stmt.executeQuery(str);

        while (rs.next()) {
            int id = rs.getInt("nAuthorId");
            String name = rs.getString("cAuthorName");
            author.setnAuthorId(id);
            author.setcAuthorName(name);
            authors.add(author);
            System.out.println(author.getnAuthorId() + " - " + author.getcAuthorName());
        }
        rs.close();
        closeConnection();
    } catch (Exception e) {
        System.out.println(e);
    }
    return authors;
}

How do check if a PHP session is empty?

You could use the count() function to see how many entries there are in the $_SESSION array. This is not good practice. You should instead set the id of the user (or something similar) to check wheter the session was initialised or not.

if( !isset($_SESSION['uid']) )
    die( "Login required." );

(Assuming you want to check if someone is logged in)

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

SET STATISTICS TIME ON

SELECT * 

FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;

SET STATISTICS TIME OFF;

And see the message tab it will look like this:

SQL Server Execution Times:

   CPU time = 0 ms,  elapsed time = 10 ms.

(778 row(s) affected)

SQL Server parse and compile time: 

   CPU time = 0 ms, elapsed time = 0 ms.

Send cookies with curl

Very annoying, no cookie file exmpale on the official website https://ec.haxx.se/http/http-cookies.

Finnaly, I find it does not work, if your file content is just copyied like this

foo1=bar;foo2=bar2

I gusess the format must looks the style said by @Agustí Sánchez . You can test it by -c to create a cookie file on a website.

So try this way, it works

curl -H "Cookie:`cat ./my.cookie`"   http://xxxx.com

You can just copy the cookie from chrome console network tab.

How to get info on sent PHP curl request

If you set CURLINFO_HEADER_OUT to true, outgoing headers are available in the array returned by curl_getinfo(), under request_header key:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_exec($ch);

$info = curl_getinfo($ch);
print_r($info['request_header']);

This will print:

GET /bar HTTP/1.1
Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
Host: foo.com
Accept: */*

Note the auth details are base64-encoded:

echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
// prints: someusername:secretpassword

Also note that username and password need to be percent-encoded to escape any URL reserved characters (/, ?, &, : and so on) they might contain:

curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));

Regular expression to extract text between square brackets

You can use the following regex globally:

\[(.*?)\]

Explanation:

  • \[ : [ is a meta char and needs to be escaped if you want to match it literally.
  • (.*?) : match everything in a non-greedy way and capture it.
  • \] : ] is a meta char and needs to be escaped if you want to match it literally.

Where does Oracle SQL Developer store connections?

for macOS

/Users/joseluisbz/.sqldeveloper/system18.1.0.095.1630/o.jdeveloper.db.connection/connections.xml

Task vs Thread differences

The Thread class is used for creating and manipulating a thread in Windows.

A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.

In the days of old (i.e. before TPL) it used to be that using the Thread class was one of the standard ways to run code in the background or in parallel (a better alternative was often to use a ThreadPool), however this was cumbersome and had several disadvantages, not least of which was the performance overhead of creating a whole new thread to perform a task in the background.

Nowadays using tasks and the TPL is a far better solution 90% of the time as it provides abstractions which allows far more efficient use of system resources. I imagine there are a few scenarios where you want explicit control over the thread on which you are running your code, however generally speaking if you want to run something asynchronously your first port of call should be the TPL.

Comparison of C++ unit test frameworks

I've recently released xUnit++, specifically as an alternative to Google Test and the Boost Test Library (view the comparisons). If you're familiar with xUnit.Net, you're ready for xUnit++.

#include "xUnit++/xUnit++.h"

FACT("Foo and Blah should always return the same value")
{
    Check.Equal("0", Foo()) << "Calling Foo() with no parameters should always return \"0\".";
    Assert.Equal(Foo(), Blah());
}

THEORY("Foo should return the same value it was given, converted to string", (int input, std::string expected),
    std::make_tuple(0, "0"),
    std::make_tuple(1, "1"),
    std::make_tuple(2, "2"))
{
    Assert.Equal(expected, Foo(input));
}

Main features:

  • Incredibly fast: tests run concurrently.
  • Portable
  • Automatic test registration
  • Many assertion types (Boost has nothing on xUnit++)
  • Compares collections natively.
  • Assertions come in three levels:
    • fatal errors
    • non-fatal errors
    • warnings
  • Easy assert logging: Assert.Equal(-1, foo(i)) << "Failed with i = " << i;
  • Test logging: Log.Debug << "Starting test"; Log.Warn << "Here's a warning";
  • Fixtures
  • Data-driven tests (Theories)
  • Select which tests to run based on:
    • Attribute matching
    • Name substring matchin
    • Test Suites

How to set time to midnight for current day?

Using some of the above recommendations, the following function and code is working for search a date range:

Set date with the time component set to 00:00:00

public static DateTime GetDateZeroTime(DateTime date)
{
    return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}

Usage

var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);

var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));

jquery data selector

If you also use jQueryUI, you get a (simple) version of the :data selector with it that checks for the presence of a data item, so you can do something like $("div:data(view)"), or $( this ).closest(":data(view)").

See http://api.jqueryui.com/data-selector/ . I don't know for how long they've had it, but it's there now!

How to quickly check if folder is empty (.NET)?

You could try Directory.Exists(path) and Directory.GetFiles(path) - probably less overhead (no objects - just strings etc).

Can you have multiline HTML5 placeholder text in a <textarea>?

There is actual a hack which makes it possible to add multiline placeholders in Webkit browsers, Chrome used to work but in more recent versions they removed it:


First add the first line of your placeholder to the html5 as usual

<textarea id="text1" placeholder="Line 1" rows="10"></textarea>

then add the rest of the line by css:

#text1::-webkit-input-placeholder::after {
    display:block;
    content:"Line 2\A Line 3";
}

If you want to keep your lines at one place you can try the following. The downside of this is that other browsers than chrome, safari, webkit-etc. don't even show the first line:

<textarea id="text2" placeholder="." rows="10"></textarea>?

then add the rest of the line by css:

#text2::-webkit-input-placeholder{
    color:transparent;
}

#text2::-webkit-input-placeholder::before {
    color:#666;
    content:"Line 1\A Line 2\A Line 3\A";
}

Demo Fiddle

It would be very great, if s.o. could get a similar demo working on Firefox.

Use a.any() or a.all()

This should also work and is a closer answer to what is asked in the question:

for i in range(len(x)):
    if valeur.item(i) <= 0.6:
        print ("this works")
    else:   
        print ("valeur is too high")

SQL Format as of Round off removing decimals

use ROUND () (See examples ) function in sql server

select round(11.6,0)

result:

12.0

ex2:

select round(11.4,0)

result:

11.0

if you don't want the decimal part, you could do

select cast(round(11.6,0) as int)

3 column layout HTML/CSS

This is less for @easwee and more for others that might have the same question:

If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.

With the current, final standard, you would be done with

.container {
    display: flex;
}

.container div {
    flex: 1;
}

.column_center {
    order: 2;
}

That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into

.container {
    display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox;      /* TWEENER - IE 10 */
    display: -webkit-flex;     /* NEW - Chrome */
    display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.container div {
    -webkit-box-flex: 1;      /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 1;         /* OLD - Firefox 19- */
    -webkit-flex: 1;          /* Chrome */
    -ms-flex: 1;              /* IE 10 */
    flex: 1;                  /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.column_center {
    -webkit-box-ordinal-group: 2;   /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-ordinal-group: 2;      /* OLD - Firefox 19- */
    -ms-flex-order: 2;              /* TWEENER - IE 10 */
    -webkit-order: 2;               /* NEW - Chrome */
    order: 2;                       /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

jsFiddle demo

Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New

PHP PDO returning single row

Just fetch. only gets one row. So no foreach loop needed :D

$row  = $STH -> fetch();

example (ty northkildonan):

$dbh = new PDO(" --- connection string --- "); 
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1"); 
$stmt->execute(); 
$row = $stmt->fetch();

window.onload vs $(document).ready()

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

Pandas: drop a level from a multi-level column index?

Another way to drop the index is to use a list comprehension:

df.columns = [col[1] for col in df.columns]

   b  c
0  1  2
1  3  4

This strategy is also useful if you want to combine the names from both levels like in the example below where the bottom level contains two 'y's:

cols = pd.MultiIndex.from_tuples([("A", "x"), ("A", "y"), ("B", "y")])
df = pd.DataFrame([[1,2, 8 ], [3,4, 9]], columns=cols)

   A     B
   x  y  y
0  1  2  8
1  3  4  9

Dropping the top level would leave two columns with the index 'y'. That can be avoided by joining the names with the list comprehension.

df.columns = ['_'.join(col) for col in df.columns]

    A_x A_y B_y
0   1   2   8
1   3   4   9

That's a problem I had after doing a groupby and it took a while to find this other question that solved it. I adapted that solution to the specific case here.

What does [STAThread] do?

It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.

This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).

Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.

Can't change table design in SQL Server 2008

You can directly add a constraint for table

ALTER TABLE TableName
ADD CONSTRAINT ConstraintName PRIMARY KEY(ColumnName)
GO 

Make sure your primary key column should not have any null values.

Option 2:

you can change your SQL Management Studio Options like

To change this option, on the Tools menu, click Options, expand Designers, and then click Table and Database Designers. Select or clear the Prevent saving changes that require the table to be re-created check box.

CSS Transition doesn't work with top, bottom, left, right

Perhaps you need to specify a top value in your css rule set, so that it will know what value to animate from.

How to print last two columns using awk

Please try this out to take into account all possible scenarios:

awk '{print $(NF-1)"\t"$NF}'  file

or

awk 'BEGIN{OFS="\t"}' file

or

awk '{print $(NF-1), $NF} {print $(NF-1), $NF}' file

Rounding a double to turn it into an int (java)

Documentation of Math.round says:

Returns the result of rounding the argument to an integer. The result is equivalent to (int) Math.floor(f+0.5).

No need to cast to int. Maybe it was changed from the past.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Xcode 5 and iOS 7: Architecture and Valid architectures

You do not need to limit your compiler to only armv7 and armv7s by removing arm64 setting from supported architectures. You just need to set Deployment target setting to 5.1.1

Important note: you cannot set Deployment target to 5.1.1 in Build Settings section because it is drop-down only with fixed values. But you can easily set it to 5.1.1 in General section of application settings by just typing the value in text field.

Replacing a character from a certain index

You can also Use below method if you have to replace string between specific index

def Replace_Substring_Between_Index(singleLine,stringToReplace='',startPos=0,endPos=1):
    try:
       singleLine = singleLine[:startPos]+stringToReplace+singleLine[endPos:]
    except Exception as e:
        exception="There is Exception at this step while calling replace_str_index method, Reason = " + str(e)
        BuiltIn.log_to_console(exception)
    return singleLine

Programmatic equivalent of default(Type)

 /// <summary>
    /// returns the default value of a specified type
    /// </summary>
    /// <param name="type"></param>
    public static object GetDefault(this Type type)
    {
        return type.IsValueType ? (!type.IsGenericType ? Activator.CreateInstance(type) : type.GenericTypeArguments[0].GetDefault() ) : null;
    }

Give all permissions to a user on a PostgreSQL database

I did the following to add a role 'eSumit' on PostgreSQL 9.4.15 database and provide all permission to this role :

CREATE ROLE eSumit;

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO eSumit;

GRANT ALL PRIVILEGES ON DATABASE "postgres" to eSumit;

ALTER USER eSumit WITH SUPERUSER;

Also checked the pg_table enteries via :

select * from pg_roles; enter image description here

Database queries snapshot : enter image description here

import sun.misc.BASE64Encoder results in error compiled in Eclipse

I had this problem on jdk1.6.0_37. This is the only JDE/JRE on my system. I don't know why, but the following solved the problem:

Project -> Properties -> Java Build Path - > Libraries

Switch radio button from Execution environment to Alernate JRE. This selects the same jdk1.6.0_37, but after clean/build the compile error disappeared.

Maybe clarification in answer from ram (Mar 16 at 9:00) has to do something with that.

How do I add a new sourceset to Gradle?

Here's what works for me as of Gradle 4.0.

sourceSets {
  integrationTest {
    compileClasspath += sourceSets.test.compileClasspath
    runtimeClasspath += sourceSets.test.runtimeClasspath
  }
}

task integrationTest(type: Test) {
  description = "Runs the integration tests."
  group = 'verification'
  testClassesDirs = sourceSets.integrationTest.output.classesDirs
  classpath = sourceSets.integrationTest.runtimeClasspath
}

As of version 4.0, Gradle now uses separate classes directories for each language in a source set. So if your build script uses sourceSets.integrationTest.output.classesDir, you'll see the following deprecation warning.

Gradle now uses separate output directories for each JVM language, but this build assumes a single directory for all classes from a source set. This behaviour has been deprecated and is scheduled to be removed in Gradle 5.0

To get rid of this warning, just switch to sourceSets.integrationTest.output.classesDirs instead. For more information, see the Gradle 4.0 release notes.

How to download all files (but not HTML) from a website using wget?

This downloaded the entire website for me:

wget --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla http://site/path/

How to find files that match a wildcard string in Java?

Try FileUtils from Apache commons-io (listFiles and iterateFiles methods):

File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
   System.out.println(files[i]);
}

To solve your issue with the TestX folders, I would first iterate through the list of folders:

File[] dirs = new File(".").listFiles(new WildcardFileFilter("Test*.java");
for (int i=0; i<dirs.length; i++) {
   File dir = dirs[i];
   if (dir.isDirectory()) {
       File[] files = dir.listFiles(new WildcardFileFilter("sample*.java"));
   }
}

Quite a 'brute force' solution but should work fine. If this doesn't fit your needs, you can always use the RegexFileFilter.

Import multiple csv files into pandas and concatenate into one DataFrame

import os

os.system("awk '(NR == 1) || (FNR > 1)' file*.csv > merged.csv")

Where NR and FNR represent the number of the line being processed.

FNR is the current line within each file.

NR == 1 includes the first line of the first file (the header), while (FNR > 1) skips the first line of each subsequent file.

PostgreSQL: Drop PostgreSQL database through command line

You can run the dropdb command from the command line:

dropdb 'database name'

Note that you have to be a superuser or the database owner to be able to drop it.

You can also check the pg_stat_activity view to see what type of activity is currently taking place against your database, including all idle processes.

SELECT * FROM pg_stat_activity WHERE datname='database name';

Note that from PostgreSQL v13 on, you can disconnect the users automatically with

DROP DATABASE dbname FORCE;

or

dropdb -f dbname

how to add script src inside a View when using Layout

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

_Layout

<!DOCTYPE html>
<html>
  <head>
    <title>...</title>
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    @RenderSection("Scripts",false/*required*/)
  </head>
  <body>
    @RenderBody()
  </body>
</html>

View

@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}

Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

String.Replace ignoring case

Extending Petrucio's answer with Regex.Escape on the search string, and escaping matched group as suggested in Steve B's answer (and some minor changes to my taste):

public static class StringExtensions
{
    public static string ReplaceIgnoreCase(this string str, string from, string to)
    {
        return Regex.Replace(str, Regex.Escape(from), to.Replace("$", "$$"), RegexOptions.IgnoreCase);
    }
}

Which will produce the following expected results:

Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // Hi $1 Universe
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe"));   // heLLo wOrld

However without performing the escapes you would get the following, which is not an expected behaviour from a String.Replace that is just case-insensitive:

Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // (heLLo) wOrld
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe"));   // Hi heLLo Universe

javascript object max size limit

There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.

The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.

To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.

Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:

var items = $.map(keys, function(item, i) {
  var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
  return
    '{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
    '" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
  '{"code":"' + code + '",'+
  '"defaultfile":"' + defaultfile + '",'+
  '"filename":"' + currentFile + '",'+
  '"lstResDef":[' + items.join(',') + ']}';

DOS: find a string, if found then run another script

We have two commands, first is "condition_command", second is "result_command". If we need run "result_command" when "condition_command" is successful (errorlevel=0):

condition_command && result_command

If we need run "result_command" when "condition_command" is fail:

condition_command || result_command

Therefore for run "some_command" in case when we have "string" in the file "status.txt":

find "string" status.txt 1>nul && some_command

in case when we have not "string" in the file "status.txt":

find "string" status.txt 1>nul || some_command

Python 3 print without parenthesis

No. That will always be a syntax error in Python 3. Consider using 2to3 to translate your code to Python 3

xcode-select active developer directory error

I was having an issue while trying to install packages using npm. I got the error: "sudo xcode-select -s /Applications//Xcode.app/Contents/Developer/"

To fix this

  • I opened Xcode.
  • Preferences
  • Locations
  • Selected the Command Lin Tools: Xcode 6.1.1

Now when installing packages with npm I no longer get errors.

How do I find the current machine's full hostname in C (hostname and domain information)?

I believe you are looking for:

gethostbyaddress

Just pass it the localhost IP.

There is also a gethostbyname function, that is also usefull.

How to split a number into individual digits in c#?

Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.

The fastest way to get what you want is probably the ToCharArray() method of a String:

var myString = "12345";

var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}

You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:

byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();

A little more performant if you're using ASCII/Unicode strings:

byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();

That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.

Get filename in batch for loop

The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %, like this:

@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF

NULL vs nullptr (Why was it replaced?)

Here is Bjarne Stroustrup's wordings,

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

How to close off a Git Branch?

Yes, just delete the branch by running git push origin :branchname. To fix a new issue later, branch off from master again.

Protecting cells in Excel but allow these to be modified by VBA script

As a workaround, you can create a hidden worksheet, which would hold the changed value. The cell on the visible, protected worksheet should display the value from the hidden worksheet using a simple formula.

You will be able to change the displayed value through the hidden worksheet, while your users won't be able to edit it.

Why Would I Ever Need to Use C# Nested Classes

A pattern that I particularly like is to combine nested classes with the factory pattern:

public abstract class BankAccount
{
  private BankAccount() {} // prevent third-party subclassing.
  private sealed class SavingsAccount : BankAccount { ... }
  private sealed class ChequingAccount : BankAccount { ... }
  public static BankAccount MakeSavingAccount() { ... }
  public static BankAccount MakeChequingAccount() { ... }
}

By nesting the classes like this, I make it impossible for third parties to create their own subclasses. I have complete control over all the code that runs in any bankaccount object. And all my subclasses can share implementation details via the base class.

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

You have to set the runtime for your web project to the Tomcat installation you are using; you can do it in the "Targeted runtimes" section of the project configuration.

In this way you will allow Eclipse to add Tomcat's Java EE Web Profile jars to the build path.

Remember that the HttpServlet class isn't in a JRE, but at least in an Enterprise Web Profile (e.g. a servlet container runtime /lib folder).

Working with time DURATION, not time of day

You can easily do this with the normal "Time" data type - just change the format!

Excels time/date format is simply 1.0 equals 1 full day (starting on 1/1/1900). So 36 hours would be 1.5. If you change the format to [h]:mm, you'll see 36:00.

Therefore, if you want to work with durations, you can simply use subtraction, e.g.

A1: Start:           36:00 (=1.5)
A2: End:             60:00 (=2.5) 
A3: Duration: =A2-A1 24:00 (=1.0)

Binding List<T> to DataGridView in WinForm

This isn't exactly the issue I had, but if anyone is looking to convert a BindingList of any type to List of the same type, then this is how it is done:

var list = bindingList.ToDynamicList();

Also, if you're assigning BindingLists of dynamic types to a DataGridView.DataSource, then make sure you declare it first as IBindingList so the above works.

Angular2 RC6: '<component> is not a known element'

I ran across this exact problem. Failed: Template parse errors: 'app-login' is not a known element... with ng test. I tried all of the above replies: nothing worked.

NG TEST SOLUTION:

Angular 2 Karma Test 'component-name' is not a known element

<= I added declarations for the offending components into beforEach(.. declarations[]) to app.component.spec.ts.

EXAMPLE app.component.spec.ts

...
import { LoginComponent } from './login/login.component';
...
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ...
      ],
      declarations: [
        AppComponent,
        LoginComponent
      ],
    }).compileComponents();
  ...

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Wait until flag=true

I took an approach along the lines of the callback solutions here, but tried to make it a bit more generic. The idea is you add functions that you need to execute after something changes to a queue. When the thing happens, you then loop through the queue, call the functions and empty the queue.

Add function to queue:

let _queue = [];

const _addToQueue = (funcToQ) => {
    _queue.push(funcToQ);
}

Execute and flush the queue:

const _runQueue = () => {
    if (!_queue || !_queue.length) {
        return;
    }

    _queue.forEach(queuedFunc => {
        queuedFunc();
    });

    _queue = [];
}

And when you invoke _addToQueue you'll want to wrap the callback:

_addToQueue(() => methodYouWantToCallLater(<pass any args here like you normally would>));

When you've met the condition, call _runQueue()

This was useful for me because I had several things that needed to wait on the same condition. And it decouples the detection of the condition from whatever needs to be executed when that condition is hit.

ReferenceError: variable is not defined

Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.

Define variable with var outside the function (and of course before it) and then assign 10 to it inside function:

var value;
$(function() {
  value = "10";
});
console.log(value); // 10

Note that you shouldn't omit the first line in this code (var value;), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;) and assigning value to a variable (variable = value;) are two different things. You can't assign value to variable that you haven't defined.

It might be irrelevant here, but $(function() {}) is a shortcut for $(document).ready(function() {}), which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined until it has loaded, so console.log(value); placed right after $(function() {}) will return undefined. In other words, it would execute in following order:

var value;
console.log(value);
value = "10";

See also:

Ant error when trying to build file, can't find tools.jar?

You need JDK for that.

Set JAVA_HOME to point to the JDK.

Update int column in table with unique incrementing values

Try something like this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

This doesn't quite make them consecutive, but it does assign new higher ids. To make them consecutive, try this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (partition by interfaceId order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

package javax.mail and javax.mail.internet do not exist

  1. Download the Java mail jars.

  2. Extract the downloaded file.

  3. Copy the ".jar" file and paste it into ProjectName\WebContent\WEB-INF\lib folder

  4. Right click on the Project and go to Properties

  5. Select Java Build Path and then select Libraries

  6. Add JARs...

  7. Select the .jar file from ProjectName\WebContent\WEB-INF\lib and click OK

    that's all

Process escape sequences in a string in Python

This is a bad way of doing it, but it worked for me when trying to interpret escaped octals passed in a string argument.

input_string = eval('b"' + sys.argv[1] + '"')

It's worth mentioning that there is a difference between eval and ast.literal_eval (eval being way more unsafe). See Using python's eval() vs. ast.literal_eval()?

Use of 'prototype' vs. 'this' in JavaScript?

The examples have very different outcomes.

Before looking at the differences, the following should be noted:

  • A constructor's prototype provides a way to share methods and values among instances via the instance's private [[Prototype]] property.
  • A function's this is set by how the function is called or by the use of bind (not discussed here). Where a function is called on an object (e.g. myObj.method()) then this within the method references the object. Where this is not set by the call or by the use of bind, it defaults to the global object (window in a browser) or in strict mode, remains undefined.
  • JavaScript is an object-oriented language, i.e. most values are objects, including functions. (Strings, numbers, and booleans are not objects.)

So here are the snippets in question:

var A = function () {
    this.x = function () {
        //do something
    };
};

In this case, variable A is assigned a value that is a reference to a function. When that function is called using A(), the function's this isn't set by the call so it defaults to the global object and the expression this.x is effective window.x. The result is that a reference to the function expression on the right-hand side is assigned to window.x.

In the case of:

var A = function () { };
A.prototype.x = function () {
    //do something
};

something very different occurs. In the first line, variable A is assigned a reference to a function. In JavaScript, all functions objects have a prototype property by default so there is no separate code to create an A.prototype object.

In the second line, A.prototype.x is assigned a reference to a function. This will create an x property if it doesn't exist, or assign a new value if it does. So the difference with the first example in which object's x property is involved in the expression.

Another example is below. It's similar to the first one (and maybe what you meant to ask about):

var A = new function () {
    this.x = function () {
        //do something
    };
};

In this example, the new operator has been added before the function expression so that the function is called as a constructor. When called with new, the function's this is set to reference a new Object whose private [[Prototype]] property is set to reference the constructor's public prototype. So in the assignment statement, the x property will be created on this new object. When called as a constructor, a function returns its this object by default, so there is no need for a separate return this; statement.

To check that A has an x property:

console.log(A.x) // function () {
                 //   //do something
                 // };

This is an uncommon use of new since the only way to reference the constructor is via A.constructor. It would be much more common to do:

var A = function () {
    this.x = function () {
        //do something
    };
};
var a = new A();

Another way of achieving a similar result is to use an immediately invoked function expression:

var A = (function () {
    this.x = function () {
        //do something
    };
}());

In this case, A assigned the return value of calling the function on the right-hand side. Here again, since this is not set in the call, it will reference the global object and this.x is effective window.x. Since the function doesn't return anything, A will have a value of undefined.

These differences between the two approaches also manifest if you're serializing and de-serializing your Javascript objects to/from JSON. Methods defined on an object's prototype are not serialized when you serialize the object, which can be convenient when for example you want to serialize just the data portions of an object, but not it's methods:

var A = function () { 
    this.objectsOwnProperties = "are serialized";
};
A.prototype.prototypeProperties = "are NOT serialized";
var instance = new A();
console.log(instance.prototypeProperties); // "are NOT serialized"
console.log(JSON.stringify(instance)); 
// {"objectsOwnProperties":"are serialized"} 

Related questions:

Sidenote: There may not be any significant memory savings between the two approaches, however using the prototype to share methods and properties will likely use less memory than each instance having its own copy.

JavaScript isn't a low-level language. It may not be very valuable to think of prototyping or other inheritance patterns as a way to explicitly change the way memory is allocated.

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

Escaping single quotes in JavaScript string for JavaScript evaluation

There are two ways to escaping the single quote in JavaScript.

1- Use double-quote or backticks to enclose the string.

Example: "fsdsd'4565sd" or `fsdsd'4565sd`.

2- Use backslash before any special character, In our case is the single quote

Example:strInputString = strInputString.replace(/ ' /g, " \\' ");

Note: use a double backslash.

Both methods work for me.

Extracting text from a PDF file using PDFMiner in python?

This works in May 2020 using PDFminer six in Python3.

Installing the package

$ pip install pdfminer.six

Importing the package

from pdfminer.high_level import extract_text

Using a PDF saved on disk

text = extract_text('report.pdf')

Or alternatively:

with open('report.pdf','rb') as f:
    text = extract_text(f)

Using PDF already in memory

If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io library:

import io

response = requests.get(url)
text = extract_text(io.BytesIO(response.content))

Performance and Reliability compared with PyPDF2

PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7

However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.

I timed text extraction with timeit on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:

PDFminer.six: 2.88 sec
PyPDF2:       0.45 sec

pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.

Playing .mp3 and .wav in Java?

I have other methods for that, the first is :

public static void playAudio(String filePath){

    try{
        InputStream mus = new FileInputStream(new File(filePath));
        AudioStream aud = new AudioStream(mus);
    }catch(Exception e){
        JOptionPane.showMessageDialig(null, "You have an Error");
    }

And the second is :

try{
    JFXPanel x = JFXPanel();
    String u = new File("021.mp3").toURI().toString();
    new MediaPlayer(new Media(u)).play();
} catch(Exception e){
    JOPtionPane.showMessageDialog(null, e);
}

And if we want to make loop to this audio we use this method.

try{
    AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
    ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
    AudioPlayer.player.start(s);
} catch(Exception ex){
    JOPtionPane.showMessageDialog(null, ex);
}

if we want to stop this loop we add this libreries in the try:

AudioPlayer.player.stop(s);

for this third method we add the folowing imports :

import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;

Bash or KornShell (ksh)?

Bash.

The various UNIX and Linux implementations have various different source level implementations of ksh, some of which are real ksh, some of which are pdksh implementations and some of which are just symlinks to some other shell that has a "ksh" personality. This can lead to weird differences in execution behavior.

At least with bash you can be sure that it's a single code base, and all you need worry about is what (usually minimum) version of bash is installed. Having done a lot of scripting on pretty much every modern (and not-so-modern) UNIX, programming to bash is more reliably consistent in my experience.

How to combine two or more querysets in a Django view?

Related, for mixing querysets from the same model, or for similar fields from a few models, Starting with Django 1.11 a QuerySet.union() method is also available:

union()

union(*other_qs, all=False)

New in Django 1.11. Uses SQL’s UNION operator to combine the results of two or more QuerySets. For example:

>>> qs1.union(qs2, qs3)

The UNION operator selects only distinct values by default. To allow duplicate values, use the all=True argument.

union(), intersection(), and difference() return model instances of the type of the first QuerySet even if the arguments are QuerySets of other models. Passing different models works as long as the SELECT list is the same in all QuerySets (at least the types, the names don’t matter as long as the types in the same order).

In addition, only LIMIT, OFFSET, and ORDER BY (i.e. slicing and order_by()) are allowed on the resulting QuerySet. Further, databases place restrictions on what operations are allowed in the combined queries. For example, most databases don’t allow LIMIT or OFFSET in the combined queries.

How can I determine if a String is non-null and not only whitespace in Groovy?

You could add a method to String to make it more semantic:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

groovy:000> foo = ''
===> 
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true

bootstrap datepicker today as default

It works fine for me...

$(document).ready(function() {
        var date = new Date();
        var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());

        $('#datepicker1').datepicker({
            format: 'dd-mm-yyyy',
            orientation: 'bottom'
        });

        $('#datepicker1').datepicker('setDate', today);

    });

How does jQuery work when there are multiple elements with the same ID value?

Having 2 elements with the same ID is not valid html according to the W3C specification.

When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.

However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.

However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.


If you absolutely must select by duplicate ID, use an attribute selector:

$('[id="a"]');

Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/

Note: if possible, you should qualify that selector with a tag selector, like this:

$('span[id="a"]');

How to tell if JRE or JDK is installed

the computer in question is a Mac.

A macOS-only solution:

/usr/libexec/java_home -v 1.8+ --exec javac -version

Where 1.8+ is Java 1.8 or higher.

Unfortunately, the java_home helper does not set the proper return code, so checking for failure requires parsing the output (e.g. 2>&1 |grep -v "Unable") which varies based on locale.

Note, Java may also exist in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin, but at time of writing this, I'm unaware of a JRE that installs there which contains javac as well.

Visual Studio debugger error: Unable to start program Specified file cannot be found

I think that what you have to check is:

  1. if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).

  2. dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).

Removing an item from a select box

I had to remove the first option from a select, with no ID, only a class, so I used this code successfully:

$('select.validation').find('option:first').remove();

initializing a boolean array in java

Arrays in Java start indexing at 0. So in your example you are referring to an element that is outside the array by one.

It should probably be something like freq[Global.iParameter[2]-1]=false;

You would need to loop through the array to initialize all of it, this line only initializes the last element.

Actually, I'm pretty sure that false is default for booleans in Java, so you might not need to initialize at all.

Best Regards

How to make HTML open a hyperlink in another window or tab?

You should be able to add

target="_blank"

like

<a href="http://www.starfall.com/" target="_blank">Starfall</a>

How to parse a CSV file in Bash?

We can parse csv files with quoted strings and delimited by say | with following code

while read -r line
do
    field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
    field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')

    echo "$field1 $field2"
done < "$csvFile"

awk parses the string fields to variables and tr removes the quote.

Slightly slower as awk is executed for each field.

How to get rid of underline for Link component of React Router?

I see you're using inline styles. textDecoration: 'none' is used in child, where in fact it should be used inside <Link> as such:

<Link to="first" style={{ textDecoration: 'none' }}>
  <MenuItem style={{ paddingLeft: 13 }}>Team 1</MenuItem>
</Link>

<Link> will essentially return a standard <a> tag, which is why we apply textDecoration rule there.

I hope that helps

How to include !important in jquery

var tabsHeight = 650;

$("tabs").attr('style', 'height: '+ tabsHeight +'px !important');

OR

#CSS
.myclass{height:650px !important;}

then

$("tabs").addClass("myclass");

How do I resize a Google Map with JavaScript after it has loaded?

The popular answer google.maps.event.trigger(map, "resize"); didn't work for me alone.

Here was a trick that assured that the page had loaded and that the map had loaded as well. By setting a listener and listening for the idle state of the map you can then call the event trigger to resize.

$(document).ready(function() {
    google.maps.event.addListener(map, "idle", function(){
        google.maps.event.trigger(map, 'resize'); 
    });
}); 

This was my answer that worked for me.

insert datetime value in sql database with c#

you can send your DateTime value into SQL as a String with its special format. this format is "yyyy-MM-dd HH:mm:ss"

Example: CurrentTime is a variable as datetime Type in SQL. And dt is a DateTime variable in .Net.

DateTime dt=DateTime.Now;
string sql = "insert into Users (CurrentTime) values (‘{0}’)";

sql = string.Format(sql, dt.ToString("yyyy-MM-dd HH:mm:ss") );

How do I escape a single quote ( ' ) in JavaScript?

    document.getElementById("something").innerHTML = "<img src=\"something\" onmouseover=\"change('ex1')\" />";

OR

    document.getElementById("something").innerHTML = '<img src="something" onmouseover="change(\'ex1\')" />';

It should be working...

How to run docker-compose up -d at system start up?

If your docker.service enabled on system startup

$ sudo systemctl enable docker

and your services in your docker-compose.yml has

restart: always

all of the services run when you reboot your system if you run below command only once

docker-compose up -d

How to set username and password for SmtpClient object in .NET?

Since not all of my clients use authenticated SMTP accounts, I resorted to using the SMTP account only if app key values are supplied in web.config file.

Here is the VB code:

sSMTPUser = ConfigurationManager.AppSettings("SMTPUser")
sSMTPPassword = ConfigurationManager.AppSettings("SMTPPassword")

If sSMTPUser.Trim.Length > 0 AndAlso sSMTPPassword.Trim.Length > 0 Then
    NetClient.Credentials = New System.Net.NetworkCredential(sSMTPUser, sSMTPPassword)

    sUsingCredentialMesg = "(Using Authenticated Account) " 'used for logging purposes
End If

NetClient.Send(Message)

What are all possible pos tags of NLTK?

The tag set depends on the corpus that was used to train the tagger. The default tagger of nltk.pos_tag() uses the Penn Treebank Tag Set.

In NLTK 2, you could check which tagger is the default tagger as follows:

import nltk
nltk.tag._POS_TAGGER
>>> 'taggers/maxent_treebank_pos_tagger/english.pickle'

That means that it's a Maximum Entropy tagger trained on the Treebank corpus.

nltk.tag._POS_TAGGER does not exist anymore in NLTK 3 but the documentation states that the off-the-shelf tagger still uses the Penn Treebank tagset.

PHP random string generator

function randomString($length = 5) {
    return substr(str_shuffle(implode(array_merge(range('A','Z'), range('a','z'), range(0,9)))), 0, $length);
}

Angular - Can't make ng-repeat orderBy work

Here's a version of @Julian Mosquera's code that also supports sorting by object key:

yourApp.filter('orderObjectBy', function () {
    return function (items, field, reverse) {
        // Build array
        var filtered = [];
        for (var key in items) {
            if (field === 'key')
                filtered.push(key);
            else
                filtered.push(items[key]);
        }
        // Sort array
        filtered.sort(function (a, b) {
            if (field === 'key')
                return (a > b ? 1 : -1);
            else
                return (a[field] > b[field] ? 1 : -1);
        });
        // Reverse array
        if (reverse)
            filtered.reverse();
        return filtered;
    };
});

How to get the Touch position in android?

@Override
public boolean onTouchEvent(MotionEvent event)
{
    int x = (int)event.getX();
    int y = (int)event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
    }

    return false;
}

The three cases are so that you can react to different types of events, in this example tapping or dragging or lifting the finger again.

Why use 'git rm' to remove a file instead of 'rm'?

Remove files from the index, or from the working tree and the index. git rm will not remove a file from just your working directory.

Here's how you might delete a file using rm -f and then remove it from your index with git rm

$ rm -f index.html
$ git status -s
 D index.html
$ git rm index.html
rm 'index.html'
$ git status -s
D  index.html

However you can do this all in one go with just git rm

$ git status -s
$ git rm index.html
rm 'index.html'
$ ls
lib vendor
$ git status -s
D  index.html

C# get and set properties for a List Collection

Your setters are strange, which is why you may be seeing a problem.

First, consider whether you even need these setters - if so, they should take a List<string>, not just a string:

set
{
    _subHead = value;
}

These lines:

newSec.subHead.Add("test string");

Are calling the getter and then call Add on the returned List<string> - the setter is not invoked.

Remove all items from RecyclerView

recyclerView.removeAllViewsInLayout();

The above line would help you remove all views from the layout.

For you:

@Override
protected void onRestart() {
    super.onRestart();

    recyclerView.removeAllViewsInLayout(); //removes all the views

    //then reload the data
    PostCall doPostCall = new PostCall(); //my AsyncTask... 
    doPostCall.execute();
}

SHA512 vs. Blowfish and Bcrypt

Blowfish is not a hashing algorithm. It's an encryption algorithm. What that means is that you can encrypt something using blowfish, and then later on you can decrypt it back to plain text.

SHA512 is a hashing algorithm. That means that (in theory) once you hash the input you can't get the original input back again.

They're 2 different things, designed to be used for different tasks. There is no 'correct' answer to "is blowfish better than SHA512?" You might as well ask "are apples better than kangaroos?"

If you want to read some more on the topic here's some links:

How to write files to assets folder or raw folder in android?

You cannot write data's to asset/Raw folder, since it is packed(.apk) and not expandable in size.

If your application need to download dependency files from server, you can go for APK Expansion Files provided by android (http://developer.android.com/guide/market/expansion-files.html).

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

How to quickly drop a user with existing privileges

The accepted answer resulted in errors for me when attempting REASSIGN OWNED BY or DROP OWNED BY. The following worked for me:

REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;
DROP USER username;

The user may have privileges in other schemas, in which case you will have to run the appropriate REVOKE line with "public" replaced by the correct schema. To show all of the schemas and privilege types for a user, I edited the \dp command to make this query:

SELECT 
  n.nspname as "Schema",
  CASE c.relkind 
    WHEN 'r' THEN 'table' 
    WHEN 'v' THEN 'view' 
    WHEN 'm' THEN 'materialized view' 
    WHEN 'S' THEN 'sequence' 
    WHEN 'f' THEN 'foreign table' 
  END as "Type"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.array_to_string(c.relacl, E'\n') LIKE '%username%';

I'm not sure which privilege types correspond to revoking on TABLES, SEQUENCES, or FUNCTIONS, but I think all of them fall under one of the three.

Visual Studio Code: Auto-refresh file changes

SUPER-SHIFT-p > File: Revert File is the only way

(where SUPER is Command on Mac and Ctrl on PC)

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

jQuery UI accordion that keeps multiple sections open?

Without jQuery-UI accordion, one can simply do this:

<div class="section">
  <div class="section-title">
    Section 1
  </div>
  <div class="section-content">
    Section 1 Content: Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
  </div>
</div>

<div class="section">
  <div class="section-title">
    Section 2
  </div>
  <div class="section-content">
    Section 2 Content: Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
  </div>
</div>

And js

$( ".section-title" ).click(function() {
    $(this).parent().find( ".section-content" ).slideToggle();
});

https://jsfiddle.net/gayan_dasanayake/6ogxL7nm/

CSS center display inline block?

This will horizontally center an inline-block element without needing to modify its parent's styles:

  display: inline-block;
  position: relative;
  // Move the element to the left by 50% of the container's width
  left: 50%; 
  // Calculates 50% of the element's width, and moves it by that
  // amount across the X-axis to the left
  transform: translateX(-50%);

How can you get the Manifest Version number from the App's (Layout) XML variables?

You can use the versionName in XML resources, such as activity layouts. First create a string resource in the app/build.gradle with the following snippet in the android node:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

So the whole build.gradle file contents may look like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0 rc3'
    defaultConfig {
        applicationId 'com.example.myapplication'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 17
        versionName '0.2.3'
        jackOptions {
            enabled true
        }
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
} 

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:support-v4:23.3.0'
}

Then you can use @string/versionName in the XML. Android Studio will mark it red, but the app will compile without issues. For example, this may be used like this in app/src/main/res/xml/preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title="About"
        android:key="pref_key_about">

        <Preference
            android:key="pref_about_build"
            android:title="Build version"
            android:summary="@string/versionName" />

    </PreferenceCategory>


</PreferenceScreen>

How to programmatically close a JFrame

This answer was given by Alex and I would like to recommend it. It worked for me and another thing it's straightforward and so simple.

setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object

What is the Swift equivalent to Objective-C's "@synchronized"?

You can sandwich statements between objc_sync_enter(obj: AnyObject?) and objc_sync_exit(obj: AnyObject?). The @synchronized keyword is using those methods under the covers. i.e.

objc_sync_enter(self)
... synchronized code ...
objc_sync_exit(self)

What is the difference between Views and Materialized Views in Oracle?

Adding to Mike McAllister's pretty-thorough answer...

Materialized views can only be set to refresh automatically through the database detecting changes when the view query is considered simple by the compiler. If it's considered too complex, it won't be able to set up what are essentially internal triggers to track changes in the source tables to only update the changed rows in the mview table.

When you create a materialized view, you'll find that Oracle creates both the mview and as a table with the same name, which can make things confusing.

Using JQuery hover with HTML image map

I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P

Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.

How to create multidimensional array

I've written a one linear for this:

[1, 3, 1, 4, 1].reduceRight((x, y) => new Array(y).fill().map(() => JSON.parse(JSON.stringify(x))), 0);

I feel however I can spend more time to make a JSON.parse(JSON.stringify())-free version which is used for cloning here.

Btw, have a look at my another answer here.

How do you get the path to the Laravel Storage folder?

For Laravel version >=5.1

storage_path()

The storage_path function returns the fully qualified path to the storage directory:

$path = storage_path();

You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:

$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');

Source: Laravel Doc

Converting JSON to XML in Java

If you have a valid dtd file for the xml then you can easily transform json to xml and xml to json using the eclipselink jar binary.

Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

The article also has a sample project (including the supporting third party jars) as a zip file which can be downloaded for reference purpose.

Reading JSON POST using PHP

you can put your json in a parameter and send it instead of put only your json in header:

$post_string= 'json_param=' . json_encode($data);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call

//execute post
$result = curl_exec($curl);

//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);

on the service side you can get your json string as a parameter:

$json_string = $_POST['json_param'];
$obj = json_decode($json_string);

then you can use your converted data as object.

Rename Pandas DataFrame Index

If you want to use the same mapping for renaming both columns and index you can do:

mapping = {0:'Date', 1:'SM'}
df.index.names = list(map(lambda name: mapping.get(name, name), df.index.names))
df.rename(columns=mapping, inplace=True)

What is the best way to add a value to an array in state

This might not directly answer your question but for the sake of those that come with states like the below

 state = {
    currentstate:[
     {
    id: 1 ,
    firstname: 'zinani',
    sex: 'male'

     }
    ]

 }

Solution

const new_value = {
    id: 2 ,
    firstname: 'san',
    sex: 'male'

     }

Replace the current state with the new value

 this.setState({ currentState: [...this.state.currentState, new_array] })

Using AES encryption in C#

//Code to encrypt Data :   
 public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv)  
         {  
           AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider();  
           //Block size : Gets or sets the block size, in bits, of the cryptographic operation.  
           dataencrypt.BlockSize = 128;  
           //KeySize: Gets or sets the size, in bits, of the secret key  
           dataencrypt.KeySize = 128;  
           //Key: Gets or sets the symmetric key that is used for encryption and decryption.  
           dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
           //IV : Gets or sets the initialization vector (IV) for the symmetric algorithm  
           dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
           //Padding: Gets or sets the padding mode used in the symmetric algorithm  
           dataencrypt.Padding = PaddingMode.PKCS7;  
           //Mode: Gets or sets the mode for operation of the symmetric algorithm  
           dataencrypt.Mode = CipherMode.CBC;  
           //Creates a symmetric AES encryptor object using the current key and initialization vector (IV).  
           ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV);  
           //TransformFinalBlock is a special function for transforming the last block or a partial block in the stream.   
           //It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of   
           //information returned at the end might be larger than a single block when padding is added.  
           byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length);  
           crypto1.Dispose();  
           //return the encrypted data  
           return encrypteddata;  
         }  

//code to decrypt data
    private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv)  
     {  

       AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();  
       keydecrypt.BlockSize = 128;  
       keydecrypt.KeySize = 128;  
       keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
       keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
       keydecrypt.Padding = PaddingMode.PKCS7;  
       keydecrypt.Mode = CipherMode.CBC;  
       ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);  

       byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);  
       crypto1.Dispose();  
       return returnbytearray;  
     }

.NET String.Format() to add commas in thousands place for a number

C# 7.1 (perhaps earlier?) makes this as easy and nice-looking as it should be, with string interpolation:

var jackpot = 1000000;
var niceNumberString = $"Jackpot is {jackpot:n}";
var niceMoneyString = $"Jackpot is {jackpot:C}";

Dynamically load a JavaScript file

I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/

var _rmod = _rmod || {}; //require module namespace
_rmod.on_ready_fn_stack = [];
_rmod.libpath = '';
_rmod.imported = {};
_rmod.loading = {
    scripts: {},
    length: 0
};

_rmod.findScriptPath = function(script_name) {
    var script_elems = document.getElementsByTagName('script');
    for (var i = 0; i < script_elems.length; i++) {
        if (script_elems[i].src.endsWith(script_name)) {
            var href = window.location.href;
            href = href.substring(0, href.lastIndexOf('/'));
            var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);
            return url.substring(href.length+1, url.length);
        }
    }
    return '';
};

_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark the root directory of your library, any library


_rmod.injectScript = function(script_name, uri, callback, prepare) {

    if(!prepare)
        prepare(script_name, uri);

    var script_elem = document.createElement('script');
    script_elem.type = 'text/javascript';
    script_elem.title = script_name;
    script_elem.src = uri;
    script_elem.async = true;
    script_elem.defer = false;

    if(!callback)
        script_elem.onload = function() {
            callback(script_name, uri);
        };

    document.getElementsByTagName('head')[0].appendChild(script_elem);
};

_rmod.requirePrepare = function(script_name, uri) {
    _rmod.loading.scripts[script_name] = uri;
    _rmod.loading.length++;
};

_rmod.requireCallback = function(script_name, uri) {
    _rmod.loading.length--;
    delete _rmod.loading.scripts[script_name];
    _rmod.imported[script_name] = uri;

    if(_rmod.loading.length == 0)
        _rmod.onReady();
};

_rmod.onReady = function() {
    if (!_rmod.LOADED) {
        for (var i = 0; i < _rmod.on_ready_fn_stack.length; i++){
            _rmod.on_ready_fn_stack[i]();
        });
        _rmod.LOADED = true;
    }
};

//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.
var require = function(script_name) {
    var np = script_name.split('.');
    if (np[np.length-1] === '*') {
        np.pop();
        np.push('_all');
    }

    script_name = np.join('.');
    var uri = _rmod.libpath + np.join('/')+'.js';
    if (!_rmod.loading.scripts.hasOwnProperty(script_name) 
     && !_rmod.imported.hasOwnProperty(script_name)) {
        _rmod.injectScript(script_name, uri, 
            _rmod.requireCallback, 
                _rmod.requirePrepare);
    }
};

var ready = function(fn) {
    _rmod.on_ready_fn_stack.push(fn);
};

// ----- USAGE -----

require('ivar.util.array');
require('ivar.util.string');
require('ivar.net.*');

ready(function(){
    //do something when required scripts are loaded
});

How to close a window using jQuery

You can only use the window.close function when you have opened the window using window.open(), so I use the following function:

function close_window(url){
    var newWindow = window.open('', '_self', ''); //open the current window
    window.close(url);
 }

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

Entity Framework Migrations renaming tables and columns

I just tried the same in EF6 (code first entity rename). I simply renamed the class and added a migration using the package manager console and voila, a migration using RenameTable(...) was automatically generated for me. I have to admit that I made sure the only change to the entity was renaming it so no new columns or renamed columns so I cannot be certain if this is an EF6 thing or just that EF was (always) able to detect such simple migrations.

How to get the android Path string to a file on Assets folder?

AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.

So, you really can't make stuff that expects a file accept an asset 'file'.

Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:

  File f = new File(getCacheDir()+"/m1.map");
  if (!f.exists()) try {

    InputStream is = getAssets().open("m1.map");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();


    FileOutputStream fos = new FileOutputStream(f);
    fos.write(buffer);
    fos.close();
  } catch (Exception e) { throw new RuntimeException(e); }

  mapView.setMapFile(f.getPath());

How to uncheck checked radio button

You might consider adding an additional radio button to each group labeled 'none' or the like. This can create a consistent user experience without complicating the development process.