Programs & Examples On #Zend feed

Get source JARs from Maven repository

Based on watching the Maven console in Eclipse (Kepler), sources will be automatically downloaded for a Maven dependency if you attempt to open a class from said Maven dependency in the editor for which you do not have the sources downloaded already. This is handy when you don't want to grab source for all of your dependencies, but you don't know which ones you want ahead of time (and you're using Eclipse).

I ended up using @GabrielRamierez's approach, but will employ @PascalThivent's approach going forward.

Regular expression that doesn't contain certain string

All you need is a reluctant quantifier:

regex: /aa.*?aa/

aabbabcaabda   => aabbabcaa

aaaaaabda      => aaaa

aabbabcaabda   => aabbabcaa

aababaaaabdaa  => aababaa, aabdaa

You could use negative lookahead, too, but in this case it's just a more verbose way accomplish the same thing. Also, it's a little trickier than gpojd made it out to be. The lookahead has to be applied at each position before the dot is allowed to consume the next character.

/aa(?:(?!aa).)*aa/

As for the approach suggested by Claudiu and finnw, it'll work okay when the sentinel string is only two characters long, but (as Claudiu acknowledged) it's too unwieldy for longer strings.

PHP "pretty print" json_encode

Here's a function to pretty up your json: pretty_json

How to embed matplotlib in pyqt - for Dummies

Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...


import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

import random

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # instead of ax.hold(False)
        self.figure.clear()

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        # ax.hold(False) # deprecated, see above

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

How to log as much information as possible for a Java Exception?

Something that I do is to have a static method that handles all exceptions and I add the log to a JOptionPane to show it to the user, but you could write the result to a file in FileWriter wraped in a BufeeredWriter. For the main static method, to catch the Uncaught Exceptions I do:

SwingUtilities.invokeLater( new Runnable() {
    @Override
    public void run() {
        //Initializations...
    }
});


Thread.setDefaultUncaughtExceptionHandler( 
    new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException( Thread t, Throwable ex ) {
            handleExceptions( ex, true );
        }
    }
);

And as for the method:

public static void handleExceptions( Throwable ex, boolean shutDown ) {
    JOptionPane.showMessageDialog( null,
        "A CRITICAL ERROR APPENED!\n",
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE );

    StringBuilder sb = new StringBuilder(ex.toString());
    for (StackTraceElement ste : ex.getStackTrace()) {
        sb.append("\n\tat ").append(ste);
    }


    while( (ex = ex.getCause()) != null ) {
        sb.append("\n");
        for (StackTraceElement ste : ex.getStackTrace()) {
            sb.append("\n\tat ").append(ste);
        }
    }

    String trace = sb.toString();

    JOptionPane.showMessageDialog( null,
        "PLEASE SEND ME THIS ERROR SO THAT I CAN FIX IT. \n\n" + trace,
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE);

    if( shutDown ) {
        Runtime.getRuntime().exit( 0 );
    }
}

In you case, instead of "screaming" to the user, you could write a log like I told you before:

String trace = sb.toString();

File file = new File("mylog.txt");
FileWriter myFileWriter = null;
BufferedWriter myBufferedWriter = null;

try {
    //with FileWriter(File file, boolean append) you can writer to 
    //the end of the file
    myFileWriter = new FileWriter( file, true );
    myBufferedWriter = new BufferedWriter( myFileWriter );

    myBufferedWriter.write( trace );
}
catch ( IOException ex1 ) {
    //Do as you want. Do you want to use recursive to handle 
    //this exception? I don't advise that. Trust me...
}
finally {
    try {
        myBufferedWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }

    try {
        myFileWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }
}

I hope I have helped.

Have a nice day. :)

How to convert integer into date object python?

Here is what I believe answers the question (Python 3, with type hints):

from datetime import date


def int2date(argdate: int) -> date:
    """
    If you have date as an integer, use this method to obtain a datetime.date object.

    Parameters
    ----------
    argdate : int
      Date as a regular integer value (example: 20160618)

    Returns
    -------
    dateandtime.date
      A date object which corresponds to the given value `argdate`.
    """
    year = int(argdate / 10000)
    month = int((argdate % 10000) / 100)
    day = int(argdate % 100)

    return date(year, month, day)


print(int2date(20160618))

The code above produces the expected 2016-06-18.

How do I find duplicates across multiple columns?

Duplicated id for pairs name and city:

select s.id, t.* 
from [stuff] s
join (
    select name, city, count(*) as qty
    from [stuff]
    group by name, city
    having count(*) > 1
) t on s.name = t.name and s.city = t.city

JavaScript displaying a float to 2 decimal places

number.parseFloat(2) works but it returns a string.

If you'd like to preserve it as a number type you can use:

Math.round(number * 100) / 100

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

The microsoft telnet.exe is not scriptable without using another script (which needs keyboard focus), as shown in another answer to this question, but there is a free

Telnet Scripting Tool v.1.0 by Albert Yale

that you can google for and which is both scriptable and loggable and can be launched from a batch file without needing keyboard focus.

The problem with telnet.exe and a second script when keyboard focus is being used is that if someone is using the computer at the time the script runs, then it is highly likely that the script will fail due to mouse clicks and keyboard use at that moment in time.

mysql server port number

If your MySQL server runs on default settings, you don't need to specify that.

Default MySQL port is 3306.

[updated to show mysql_error() usage]

$conn = mysql_connect($dbhost, $dbuser, $dbpass)
    or die('Error connecting to mysql: '.mysql_error());

Android - styling seek bar

Google have made this easier in SDK 21. Now we have attributes for specifying the thumb tint colors:

android:thumbTint
android:thumbTintMode
android:progressTint

http://developer.android.com/reference/android/widget/AbsSeekBar.html#attr_android:thumbTint http://developer.android.com/reference/android/widget/AbsSeekBar.html#attr_android:thumbTintMode

Shell command to sum integers, one per line?

C (not simplified)

seq 1 10 | tcc -run <(cat << EOF
#include <stdio.h>
int main(int argc, char** argv) {
    int sum = 0;
    int i = 0;
    while(scanf("%d", &i) == 1) {
        sum = sum + i;
    }
    printf("%d\n", sum);
    return 0;
}
EOF)

How to Get enum item name from its value

I have had excellent success with a technique which resembles the X macros pointed to by @RolandXu. We made heavy use of the stringize operator, too. The technique mitigates the maintenance nightmare when you have an application domain where items appear both as strings and as numerical tokens.

It comes in particularily handy when machine readable documentation is available so that the macro X(...) lines can be auto-generated. A new documentation would immediately result in a consistent program update covering the strings, enums and the dictionaries translating between them in both directions. (We were dealing with PCL6 tokens).

And while the preprocessor code looks pretty ugly, all those technicalities can be hidden in the header files which never have to be touched again, and neither do the source files. Everything is type safe. The only thing that changes is a text file containing all the X(...) lines, and that is possibly auto generated.

Download file through an ajax call php

@joe : Many thanks, this was a good heads up!

I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file

So that's how I did it (using JQuery to handle the AJAX request):

  1. Initial post request:

    var parameters = {
         pid     : "mypid",
       "files[]": ["file1.jpg","file2.jpg","file3.jpg"]
    }

    var options = { url: "request/url",//replace with your request url type: "POST",//replace with your request type data: parameters,//see above context: document.body,//replace with your contex success: function(data){ if (data) { if (data.path) { //Create an hidden iframe, with the 'src' attribute set to the created ZIP file. var dlif = $('<iframe/>',{'src':data.path}).hide(); //Append the iFrame to the context this.append(dlif); } else if (data.error) { alert(data.error); } else { alert('Something went wrong'); } } } }; $.ajax(options);

The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:

 //Code to create the zip file
 //......
 //Id of the file
 $zipid = "myzipfile.zip"
 //Download Link - it can be prettier
 $dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
 //JSON response to be handled on the client side
 $result = '{"success":1,"path":"'.$dlink.'","error":null}';
 header('Content-type: application/json;');
 echo $result;

The "request/download" can perform some security checks, if needed, and generate the file transfer:

$fn = $_GET['file'];
if ($fn) {
  //Perform security checks
  //.....check user session/role/whatever
  $result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
  if (file_exists($result)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename='.basename($result));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($result));
    ob_clean();
    flush();
    readfile($result);
    @unlink($result);
  }

}

MySQL selecting yesterday's date

Last or next date, week, month & year calculation. It might be helpful for anyone.

Current Date:

select curdate();

Yesterday:

select subdate(curdate(), 1)

Tomorrow:

select adddate(curdate(), 1)

Last 1 week:

select between subdate(curdate(), 7) and subdate(curdate(), 1)

Next 1 week:

between adddate(curdate(), 7) and adddate(curdate(), 1)

Last 1 month:

between subdate(curdate(), 30) and subdate(curdate(), 1)

Next 1 month:

between adddate(curdate(), 30) and adddate(curdate(), 1)

Current month:

subdate(curdate(),day(curdate())-1) and last_day(curdate());

Last 1 year:

between subdate(curdate(), 365) and subdate(curdate(), 1)

Next 1 year:

between adddate(curdate(), 365) and adddate(curdate(), 1)

VS 2017 Metadata file '.dll could not be found

In my case I was facing same error. One of my project solution was referring an assembly from different NuGet location. I just changed it to correct location to solve this error and rebuild. and wow the project get build successfully and all other error gone away.

Java Project: Failed to load ApplicationContext

I had the same problem, and I was using the following plugin for tests:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <useFile>true</useFile>
        <includes>
            <include>**/*Tests.java</include>
            <include>**/*Test.java</include>
        </includes>
        <excludes>
            <exclude>**/Abstract*.java</exclude>
        </excludes>
        <junitArtifactName>junit:junit</junitArtifactName>
        <parallel>methods</parallel>
        <threadCount>10</threadCount>
    </configuration>
</plugin>

The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.

After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:

    <parallel>methods</parallel>
    <threadCount>10</threadCount>

Hope that this helps someone out!

How to delete from multiple tables in MySQL?

I don't have a mysql database to test on at the moment, but have you tried specifying what to delete prior to the from clause? For example:

DELETE p, pa FROM `pets` p,
        `pets_activities` pa
  WHERE p.`order` > :order
    AND p.`pet_id` = :pet_id
    AND pa.`id` = p.`pet_id`

I think the syntax you used is limited to newer versions of mysql.

Android studio - Failed to find target android-18

If you had the problem, opened SDK manager, installed the requested updates, returned to Android Studio and had the problem again, IT IS RECOMMENDED TO RESTART ANDROID STUDIO befor trying anything else.

Gradle will run automatically and chances are that your problem will be over. You will very possibly be told install the appropriate SDK TOOLS package, which is found in your SDK MANAGER under the second tab (sdk's are not the same as sdk tools, they are complementary packages).

You don't even need to hunt the tools package, if you click on the link under the error message, Android Studio should call SDK Manager to install the package automatically.

Restart Android Studio again and you should be up and running much faster than if you attempted workarounds.

RULE OF THUMB> restart your application before messing with options and configurations.

HTML Script tag: type or language (or omit both)?

HTML4/XHTML1 requires

<script type="...">...</script>

HTML5 faces the fact that there is only one scripting language on the web, and allows

<script>...</script>

The latter works in any browser that supports scripting (NN2+).

Pad left or right with string.format (not padleft or padright) with arbitrary string

You could encapsulate the string in a struct that implements IFormattable

public struct PaddedString : IFormattable
{
   private string value;
   public PaddedString(string value) { this.value = value; }

   public string ToString(string format, IFormatProvider formatProvider)
   { 
      //... use the format to pad value
   }

   public static explicit operator PaddedString(string value)
   {
     return new PaddedString(value);
   }
}

Then use this like that :

 string.Format("->{0:x20}<-", (PaddedString)"Hello");

result:

"->xxxxxxxxxxxxxxxHello<-"

Android camera intent

Try the following I found here

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}

How to define a variable in a Dockerfile?

Late to the party, but if you don't want to expose environment variables, I guess it's easier to do something like this:

RUN echo 1 > /tmp/__var_1
RUN echo `cat /tmp/__var_1`
RUN rm -f /tmp/__var_1

I ended up doing it because we host private npm packages in aws codeartifact:

RUN aws codeartifact get-authorization-token --output text > /tmp/codeartifact.token
RUN npm config set //company-123456.d.codeartifact.us-east-2.amazonaws.com/npm/internal/:_authToken=`cat /tmp/codeartifact.token`
RUN rm -f /tmp/codeartifact.token

And here ARG cannot work and i don't want to use ENV because i don't want to expose this token to anything else

Best way to serialize/unserialize objects in JavaScript?

I've added yet another JavaScript serializer repo to GitHub.

Rather than take the approach of serializing and deserializing JavaScript objects to an internal format the approach here is to serialize JavaScript objects out to native JavaScript. This has the advantage that the format is totally agnostic from the serializer, and the object can be recreated simply by calling eval().

https://github.com/iconico/JavaScript-Serializer

Run Button is Disabled in Android Studio

Above answer didn't work for me, just do click File -> Invalidate/cache -> Invalidate and Restart.

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

Get a list of resources from classpath directory

Custom Scanner

Implement your own scanner. For example:

(limitations of this solution are mentioned in the comments)

private List<String> getResourceFiles(String path) throws IOException {
    List<String> filenames = new ArrayList<>();

    try (
            InputStream in = getResourceAsStream(path);
            BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
        String resource;

        while ((resource = br.readLine()) != null) {
            filenames.add(resource);
        }
    }

    return filenames;
}

private InputStream getResourceAsStream(String resource) {
    final InputStream in
            = getContextClassLoader().getResourceAsStream(resource);

    return in == null ? getClass().getResourceAsStream(resource) : in;
}

private ClassLoader getContextClassLoader() {
    return Thread.currentThread().getContextClassLoader();
}

Spring Framework

Use PathMatchingResourcePatternResolver from Spring Framework.

Ronmamo Reflections

The other techniques might be slow at runtime for huge CLASSPATH values. A faster solution is to use ronmamo's Reflections API, which precompiles the search at compile time.

Regular Expression to get all characters before "-"

I dont think you need regex to achieve this. I would look at the SubString method along with the indexOf method. If you need more help, add a comment showing what you have attempted and I will offer more help.

0xC0000005: Access violation reading location 0x00000000

This line looks suspicious:

invaders[i] = inv;

You're never incrementing i, so you keep assigning to invaders[0]. If this is just an error you made when reducing your code to the example, check how you calculate i in the real code; you could be exceeding the size of invaders.

If as your comment suggests, you're creating 55 invaders, then check that invaders has been initialised correctly to handle this number.

What's the difference between "super()" and "super(props)" in React when using es6 classes?

When implementing the constructor() function inside a React component, super() is a requirement. Keep in mind that your MyComponent component is extending or borrowing functionality from the React.Component base class.

This base class has a constructor() function of its own that has some code inside of it, to setup our React component for us.

When we define a constructor() function inside our MyComponent class, we are essentially, overriding or replacing the constructor() function that is inside the React.Component class, but we still need to ensure that all the setup code inside of this constructor() function still gets called.

So to ensure that the React.Component’s constructor() function gets called, we call super(props). super(props) is a reference to the parents constructor() function, that’s all it is.

We have to add super(props) every single time we define a constructor() function inside a class-based component.

If we don’t we will see an error saying that we have to call super(props).

The entire reason for defining this constructor() funciton is to initialize our state object.

So in order to initialize our state object, underneath the super call I am going to write:

class App extends React.Component {
  constructor(props) {
      super(props);

      this.state = {};
   }

  // React says we have to define render()
  render() {
    return <div>Hello world</div>;
  }
};

So we have defined our constructor() method, initialized our state object by creating a JavaScript object, assigning a property or key/value pair to it, assigning the result of that to this.state. Now of course this is just an example here so I have not really assigned a key/value pair to the state object, its just an empty object.

C# DateTime to "YYYYMMDDHHMMSS" format

This site has great examples check it out

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}",      dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}",      dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}",      dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",          dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",               dt);  // "5 05"            minute
String.Format("{0:s ss}",               dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}",      dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}",      dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",               dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",           dt);  // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}",           dt);  // "3/9/2008"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}",   dt);  // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}",           dt);  // "03/09/08"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"

Standard DateTime Formatting

String.Format("{0:t}", dt);  // "4:05 PM"                           ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                          ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                        LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"            LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"    LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                  ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"               ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                          MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                       YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"     RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"               SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"              UniversalSortableDateTime

/*
Specifier   DateTimeFormatInfo property     Pattern value (for en-US culture)
    t           ShortTimePattern                    h:mm tt
    d           ShortDatePattern                    M/d/yyyy
    T           LongTimePattern                     h:mm:ss tt
    D           LongDatePattern                     dddd, MMMM dd, yyyy
    f           (combination of D and t)            dddd, MMMM dd, yyyy h:mm tt
    F           FullDateTimePattern                 dddd, MMMM dd, yyyy h:mm:ss tt
    g           (combination of d and t)            M/d/yyyy h:mm tt
    G           (combination of d and T)            M/d/yyyy h:mm:ss tt
    m, M        MonthDayPattern                     MMMM dd
    y, Y        YearMonthPattern                    MMMM, yyyy
    r, R        RFC1123Pattern                      ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
    s           SortableDateTi­mePattern             yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
    u           UniversalSorta­bleDateTimePat­tern    yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
                                                    (*) = culture independent   
*/

Update using c# 6 string interpolation format

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

$"{dt:y yy yyy yyyy}";  // "8 08 008 2008"   year
$"{dt:M MM MMM MMMM}";  // "3 03 Mar March"  month
$"{dt:d dd ddd dddd}";  // "9 09 Sun Sunday" day
$"{dt:h hh H HH}";      // "4 04 16 16"      hour 12/24
$"{dt:m mm}";           // "5 05"            minute
$"{dt:s ss}";           // "7 07"            second
$"{dt:f ff fff ffff}";  // "1 12 123 1230"   sec.fraction
$"{dt:F FF FFF FFFF}";  // "1 12 123 123"    without zeroes
$"{dt:t tt}";           // "P PM"            A.M. or P.M.
$"{dt:z zz zzz}";       // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
$"{dt:M/d/yyyy}";    // "3/9/2008"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

// day/month names
$"{dt:ddd, MMM d, yyyy}";    // "Sun, Mar 9, 2008"
$"{dt:dddd, MMMM d, yyyy}";  // "Sunday, March 9, 2008"

// two/four digit year
$"{dt:MM/dd/yy}";    // "03/09/08"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

Create list of single item repeated N times

As others have pointed out, using the * operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never used, you can use the anonymous underscore variable.

[e for _ in xrange(n)]

VBA Convert String to Date

Try using Replace to see if it will work for you. The problem as I see it which has been mentioned a few times above is the CDate function is choking on the periods. You can use replace to change them to slashes. To answer your question about a Function in vba that can parse any date format, there is not any you have very limited options.

Dim current as Date, highest as Date, result() as Date 
For Each itemDate in DeliveryDateArray
    Dim tempDate As String
    itemDate = IIf(Trim(itemDate) = "", "0", itemDate) 'Added per OP's request.
    tempDate = Replace(itemDate, ".", "/")
    current = Format(CDate(tempDate),"dd/mm/yyyy")
    if current > highest then 
        highest = current 
    end if 
    ' some more operations an put dates into result array 
Next itemDate 
'After activating final sheet... 
Range("A1").Resize(UBound(result), 1).Value = Application.Transpose(result) 

Cast object to T

try

if (readData is T)
    return (T)(object)readData;

How do I auto size columns through the Excel interop objects?

Add this at your TODO point:

aRange.Columns.AutoFit();

Iterating over all the keys of a map

A Type agnostic solution:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := s.MapIndex(key).Interface()
    fmt.Println("Key:", key, "Value:", value)
}  

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

AGE is defined as "42" so the line:

str += "Do you feel " + AGE + " years old?";

is converted to:

str += "Do you feel " + "42" + " years old?";

Which isn't valid since "Do you feel " and "42" are both const char[]. To solve this, you can make one a std::string, or just remove the +:

// 1.
str += std::string("Do you feel ") + AGE + " years old?";

// 2.
str += "Do you feel " AGE " years old?";

Search for string and get count in vi editor

I suggest doing:

  1. Search either with * to do a "bounded search" for what's under the cursor, or do a standard /pattern search.
  2. Use :%s///gn to get the number of occurrences. Or you can use :%s///n to get the number of lines with occurrences.

** I really with I could find a plug-in that would giving messaging of "match N of N1 on N2 lines" with every search, but alas.

Note: Don't be confused by the tricky wording of the output. The former command might give you something like 4 matches on 3 lines where the latter might give you 3 matches on 3 lines. While technically accurate, the latter is misleading and should say '3 lines match'. So, as you can see, there really is never any need to use the latter ('n' only) form. You get the same info, more clearly, and more by using the 'gn' form.

Angular 2 filter/search list

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

How to set cache: false in jQuery.get call

Add the parameter yourself.

$.get(url,{ "_": $.now() }, function(rdata){
  console.log(rdata);
});

As of jQuery 3.0, you can now do this:

$.get({
  url: url, 
  cache: false
}).then(function(rdata){
  console.log(rdata);
});

Laravel Redirect Back with() Message

For laravel 5.6.*

While trying some of the provided answers in Laravel 5.6.*, it's clear there has been some improvements which I am going to post here to make things easy for those that could not find a solution with the rest of the answers.

STEP 1:

Go to your Controller File and Add this before the class:

use Illuminate\Support\Facades\Redirect;

STEP 2: Add this where you want to return the redirect.

 return Redirect()->back()->with(['message' => 'The Message']);

STEP 3: Go to your blade file and edit as follows

@if (Session::has('message'))
<div class="alert alert-error>{{Session::get('message')}}</div>
 @endif

Then test and thank me later.

This should work with laravel 5.6.* and possibly 5.7.*

How-to turn off all SSL checks for postman for a specific site

This is not the exact answer to this question, but those who are not able to find setting popup. Their is two ways to open setting pop up.

  1. Way 1

  2. Way 2

Use images instead of radio buttons

Just using a class to only hide some...based on https://stackoverflow.com/a/17541916/1815624

_x000D_
_x000D_
/* HIDE RADIO */_x000D_
.hiddenradio [type=radio] { _x000D_
  position: absolute;_x000D_
  opacity: 0;_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
}_x000D_
_x000D_
/* IMAGE STYLES */_x000D_
.hiddenradio [type=radio] + img {_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
/* CHECKED STYLES */_x000D_
.hiddenradio [type=radio]:checked + img {_x000D_
  outline: 2px solid #f00;_x000D_
}
_x000D_
<div class="hiddenradio">_x000D_
<label>_x000D_
  <input type="radio" name="test" value="small" checked>_x000D_
  <img src="http://placehold.it/40x60/0bf/fff&text=A">_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
  <input type="radio" name="test" value="big">_x000D_
  <img src="http://placehold.it/40x60/b0f/fff&text=B">_x000D_
</label>_x000D_
</div>_x000D_
_x000D_
<div class="">_x000D_
<label>_x000D_
  <input type="radio" name="test" value="small" checked>_x000D_
  <img src="http://placehold.it/40x60/0bf/fff&text=A">_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
  <input type="radio" name="test" value="big">_x000D_
  <img src="http://placehold.it/40x60/b0f/fff&text=B">_x000D_
</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Flask Download a File

You need to make sure that the value you pass to the directory argument is an absolute path, corrected for the current location of your application.

The best way to do this is to configure UPLOAD_FOLDER as a relative path (no leading slash), then make it absolute by prepending current_app.root_path:

@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
    return send_from_directory(directory=uploads, filename=filename)

It is important to reiterate that UPLOAD_FOLDER must be relative for this to work, e.g. not start with a /.

A relative path could work but relies too much on the current working directory being set to the place where your Flask code lives. This may not always be the case.

How to make join queries using Sequelize on Node.js

In my case i did following thing. In the UserMaster userId is PK and in UserAccess userId is FK of UserMaster

UserAccess.belongsTo(UserMaster,{foreignKey: 'userId'});
UserMaster.hasMany(UserAccess,{foreignKey : 'userId'});
var userData = await UserMaster.findAll({include: [UserAccess]});

Table scroll with HTML and CSS

For whatever it's worth now: here is yet another solution:

  • create two divs within a display: inline-block
  • in the first div, put a table with only the header (header table tabhead)
  • in the 2nd div, put a table with header and data (data table / full table tabfull)
  • use JavaScript, use setTimeout(() => {/*...*/}) to execute code after render / after filling the table with results from fetch
  • measure the width of each th in the data table (using clientWidth)
  • apply the same width to the counterpart in the header table
  • set visibility of the header of the data table to hidden and set the margin top to -1 * height of data table thead pixels

With a few tweaks, this is the method to use (for brevity / simplicity, I used d3js, the same operations can be done using plain DOM):

setTimeout(() => { // pass one cycle
  d3.select('#tabfull')
    .style('margin-top', (-1 * d3.select('#tabscroll').select('thead').node().getBoundingClientRect().height) + 'px')
    .select('thead')
      .style('visibility', 'hidden');
  let widths=[]; // really rely on COMPUTED values
  d3.select('#tabfull').select('thead').selectAll('th')
    .each((n, i, nd) => widths.push(nd[i].clientWidth));
  d3.select('#tabhead').select('thead').selectAll('th')
    .each((n, i, nd) => d3.select(nd[i])
          .style('padding-right', 0)
          .style('padding-left', 0)
          .style('width', widths[i]+'px'));
})

Waiting on render cycle has the advantage of using the browser layout engine thoughout the process - for any type of header; it's not bound to special condition or cell content lengths being somehow similar. It also adjusts correctly for visible scrollbars (like on Windows)

I've put up a codepen with a full example here: https://codepen.io/sebredhh/pen/QmJvKy

Login failed for user 'DOMAIN\MACHINENAME$'

I got this error trying to test a solution using the following

string cn = "Data Source=[servername];Integrated Security=true;Initial Catalog=[dbname];";

The way I solved was: I had to open Visual Studio and run it under another account, because the account I was using to open was not my Admin account.

So if your problem is similar to mine: pin the VS to the task bar, then use Shift and Right Click to open the menu so you can open VS as another user. enter image description here

How to create Drawable from resource

If you are trying to get the drawable from the view where the image is set as,

ivshowing.setBackgroundResource(R.drawable.one);

then the drawable will return only null value with the following code...

   Drawable drawable = (Drawable) ivshowing.getDrawable();

So, it's better to set the image with the following code, if you wanna retrieve the drawable from a particular view.

 ivshowing.setImageResource(R.drawable.one);

only then the drawable will we converted exactly.

Convert base64 png data to javascript file objects

Way 1: only works for dataURL, not for other types of url.

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
    mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename, {type:mimeType});})
    );
}

//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
    console.log(file);
})

Both works in Chrome and Firefox.

WebDriver: check if an element exists?

As I understand it, this is the default way of using the web driver.

Split page vertically using CSS

Alternatively, you can also use a special function known as the linear-gradient() function to split browser screen into two equal halves. Check out the following code snippet:

body
{
  background-image:linear-gradient(90deg, lightblue 50%, skyblue 50%);
}

Here, linear-gradient() function accepts three arguments

  1. 90deg for vertical division of screen.( Similarly, you can use 180deg for horizontal division of screen)
  2. lightblue color is used to represent the left half of the screen.
  3. skyblue color has been used to represent the right half of the split screen. Here, 50% has been used for equal division of the browser screen. You can use any other value if you don't want an equal division of the screen. Hope this helps. :) Happy Coding!

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

You can take the SelectedItem and cast it back to your class and access its properties.

 MessageBox.Show(((ComboboxItem)ComboBox_Countries_In_Silvers.SelectedItem).Value);

Edit You can try using DataTextField and DataValueField, I used it with DataSource.

ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";

Git diff against a stash

FWIW This may be a bit redundant to all the other answers and is very similar to the accepted answer which is spot on; but maybe it will help someone out.

git stash show --help will give you all you should need; including stash show info.

show [<stash>]

Show the changes recorded in the stash as a diff between the stashed state and its original parent. When no is given, shows the latest one. By default, the command shows the diffstat, but it will accept any format known to git diff (e.g., git stash show -p stash@{1} to view the second most recent stash in patch form). You can use stash.showStat and/or stash.showPatch config variables to change the default behavior.

How can I preview a merge in git?

If you're like me, you're looking for equivalent to svn update -n. The following appears to do the trick. Note that make sure to do a git fetch first so that your local repo has the appropriate updates to compare against.

$ git fetch origin
$ git diff --name-status origin/master
D       TableAudit/Step0_DeleteOldFiles.sh
D       TableAudit/Step1_PopulateRawTableList.sh
A       manbuild/staff_companies.sql
M       update-all-slave-dbs.sh

or if you want a diff from your head to the remote:

$ git fetch origin
$ git diff origin/master

IMO this solution is much easier and less error prone (and therefore much less risky) than the top solution which proposes "merge then abort".

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data

Convert datetime to valid JavaScript date

One can use the getmonth and getday methods to get only the date.

Here I attach my solution:

_x000D_
_x000D_
var fullDate = new Date(); console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
    twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
    twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
_x000D_
_x000D_

How to find my php-fpm.sock?

I know this is old questions but since I too have the same problem just now and found out the answer, thought I might share it. The problem was due to configuration at pood.d/ directory.

Open

/etc/php5/fpm/pool.d/www.conf

find

listen = 127.0.0.1:9000

change to

listen = /var/run/php5-fpm.sock

Restart both nginx and php5-fpm service afterwards and check if php5-fpm.sock already created.

Simple way to transpose columns and rows in SQL?

I was able to use Paco Zarate's solution and it works beautifully. I did have to add one line ("SET ANSI_WARNINGS ON"), but that may be something unique to the way I used it or called it. There is a problem with my usage and I hope someone can help me with it:

The solution works only with an actual SQL table. I tried it with a temporary table and also an in-memory (declared) table but it doesn't work with those. So in my calling code I create a table on my SQL database and then call SQLTranspose. Again, it works great. It's just what I want. Here's my problem:

In order for the overall solution to be truly dynamic I need to create that table where I temporarily store the prepared information that I'm sending to SQLTranspose "on the fly", and then delete that table once SQLTranspose is called. The table deletion is presenting a problem with my ultimate implementation plan. The code needs to run from an end-user application (a button on a Microsoft Access form/menu). When I use this SQL process (create a SQL table, call SQLTranspose, delete SQL table) the end user application hits an error because the SQL account used does not have the rights to drop a table.

So I figure there are a few possible solutions:

  1. Find a way to make SQLTranspose work with a temporary table or a declared table variable.

  2. Figure out another method for the transposition of rows and columns that doesn't require an actual SQL table.

  3. Figure out an appropriate method of allowing the SQL account used by my end users to drop a table. It's a single shared SQL account coded into my Access application. It appears that permission is a dbo-type privilege that cannot be granted.

I recognize that some of this may warrant another, separate thread and question. However, since there is a possibility that one solution may be simply a different way to do the transposing of rows and columns I'll make my first post here in this thread.

EDIT: I also did replace sum(value) with max(value) in the 6th line from the end, as Paco suggested.

EDIT:

I figured out something that works for me. I don't know if it's the best answer or not.

I have a read-only user account that is used to execute strored procedures and therefore generate reporting output from a database. Since the SQLTranspose function I created will only work with a "legitimate" table (not a declared table and not a temporary table) I had to figure out a way for a read-only user account to create (and then later delete) a table.

I reasoned that for my purposes it's okay for the user account to be allowed to create a table. The user still could not delete the table though. My solution was to create a schema where the user account is authorized. Then whenever I create, use, or delete that table refer it with the schema specified.

I first issued this command from a 'sa' or 'sysadmin' account: CREATE SCHEMA ro AUTHORIZATION

When any time I refer to my "tmpoutput" table I specify it like this example:

drop table ro.tmpoutput

PHP new line break in emails

I know this is an old question but anyway it might help someone.

I tend to use PHP_EOL for this purposes (due to cross-platform compatibility).

echo "line 1".PHP_EOL."line 2".PHP_EOL;

If you're planning to show the result in a browser then you have to use "<br>".

EDIT: since your exact question is about emails, things are a bit different. For pure text emails see Brendan Bullen's accepted answer. For HTML emails you simply use HTML formatting.

How to delete zero components in a vector in Matlab?

Data

a=[0  3   0   0   7   10   3   0   1   0   7   7   1   7   4]

Do

aa=nonzeros(a)'

Result

aa=[3   7   10   3   1   7   7   1   7   4]

Iterate two Lists or Arrays with one ForEach statement in C#

This is known as a Zip operation and will be supported in .NET 4.

With that, you would be able to write something like:

var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { "one", "two", "three", "four" };

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
    Console.WriteLine(nw.Number + nw.Word);
}

As an alternative to the anonymous type with the named fields, you can also save on braces by using a Tuple and its static Tuple.Create helper:

foreach (var nw in numbers.Zip(words, Tuple.Create)) 
{
    Console.WriteLine(nw.Item1 + nw.Item2);
}

Effective method to hide email from spam bots

This is probably the best and easiest email protector on the internet. Very simple yet it has the ability to add all the bells and whistles.

Protecting Email on webpages

Uses JavaScript. I've been using it successfully for years.

How to make <input type="file"/> accept only these types?

IMPORTANT UPDATE:

Due to use of only application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint... allows only till 2003 MS products, and not newest. I've found this:

application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.openxmlformats-officedocument.presentationml.presentation

And that includes the new ones. For other files, you can retrieve the MIME TYPE in your file by this way (pardon the lang)(in MIME list types, there aren't this ones):

enter image description here

You can select & copy the type of content

Run a vbscript from another vbscript

As Martin's Answer didn't work at all for me ("File not found") and atesio's Answer does not allow to call two scripts which include repeating variable definitions, here is another alternative which finally worked for me:

filepath =  Chr(34) & "C:\...\helloworld.vbs" & Chr(34)
Set objshell= CreateObject("WScript.Shell") 
objshell.Run "wscript " & filepath, , True
Set objshell= Nothing

(Windows 8.1)

Add one year in current date PYTHON

This is what I do when I need to add months or years and don't want to import more libraries. Just create a datetime.date() object, call add_month(date) to add a month and add_year(date) to add a year.

import datetime
__author__ = 'Daniel Margarido'


# Check if the int given year is a leap year
# return true if leap year or false otherwise
def is_leap_year(year):
    if (year % 4) == 0:
        if (year % 100) == 0:
            if (year % 400) == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False


THIRTY_DAYS_MONTHS = [4, 6, 9, 11]
THIRTYONE_DAYS_MONTHS = [1, 3, 5, 7, 8, 10, 12]

# Inputs -> month, year Booth integers
# Return the number of days of the given month
def get_month_days(month, year):
    if month in THIRTY_DAYS_MONTHS:   # April, June, September, November
        return 30
    elif month in THIRTYONE_DAYS_MONTHS:   # January, March, May, July, August, October, December
        return 31
    else:   # February
        if is_leap_year(year):
            return 29
        else:
            return 28

# Checks the month of the given date
# Selects the number of days it needs to add one month
# return the date with one month added
def add_month(date):
    current_month_days = get_month_days(date.month, date.year)
    next_month_days = get_month_days(date.month + 1, date.year)

    delta = datetime.timedelta(days=current_month_days)
    if date.day > next_month_days:
        delta = delta - datetime.timedelta(days=(date.day - next_month_days) - 1)

    return date + delta


def add_year(date):
    if is_leap_year(date.year):
        delta = datetime.timedelta(days=366)
    else:
        delta = datetime.timedelta(days=365)

    return date + delta


# Validates if the expected_value is equal to the given value
def test_equal(expected_value, value):
    if expected_value == value:
        print "Test Passed"
        return True

    print "Test Failed : " + str(expected_value) + " is not equal to " str(value)
    return False

# Test leap year
print "---------- Test leap year ----------"
test_equal(True, is_leap_year(2012))
test_equal(True, is_leap_year(2000))
test_equal(False, is_leap_year(1900))
test_equal(False, is_leap_year(2002))
test_equal(False, is_leap_year(2100))
test_equal(True, is_leap_year(2400))
test_equal(True, is_leap_year(2016))

# Test add month
print "---------- Test add month ----------"
test_equal(datetime.date(2016, 2, 1), add_month(datetime.date(2016, 1, 1)))
test_equal(datetime.date(2016, 6, 16), add_month(datetime.date(2016, 5, 16)))
test_equal(datetime.date(2016, 3, 15), add_month(datetime.date(2016, 2, 15)))
test_equal(datetime.date(2017, 1, 12), add_month(datetime.date(2016, 12, 12)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 31)))
test_equal(datetime.date(2015, 3, 1), add_month(datetime.date(2015, 1, 31)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 30)))
test_equal(datetime.date(2016, 4, 30), add_month(datetime.date(2016, 3, 30)))
test_equal(datetime.date(2016, 5, 1), add_month(datetime.date(2016, 3, 31)))

# Test add year
print "---------- Test add year ----------"
test_equal(datetime.date(2016, 2, 2), add_year(datetime.date(2015, 2, 2)))
test_equal(datetime.date(2001, 2, 2), add_year(datetime.date(2000, 2, 2)))
test_equal(datetime.date(2100, 2, 2), add_year(datetime.date(2099, 2, 2)))
test_equal(datetime.date(2101, 2, 2), add_year(datetime.date(2100, 2, 2)))
test_equal(datetime.date(2401, 2, 2), add_year(datetime.date(2400, 2, 2)))

How do I divide in the Linux console?

you can also use perl -e

perl -e 'print 67/8'

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

go to "Project-Properties-Configuration Properties-Linker-input-Additional dependencies" then go to the end and type ";ws2_32.lib".

How to redirect output of an already running process

See Redirecting Output from a Running Process.

Firstly I run the command cat > foo1 in one session and test that data from stdin is copied to the file. Then in another session I redirect the output.

Firstly find the PID of the process:

$ ps aux | grep cat
rjc 6760 0.0 0.0 1580 376 pts/5 S+ 15:31 0:00 cat

Now check the file handles it has open:

$ ls -l /proc/6760/fd
total 3
lrwx—— 1 rjc rjc 64 Feb 27 15:32 0 -> /dev/pts/5
l-wx—— 1 rjc rjc 64 Feb 27 15:32 1 -> /tmp/foo1
lrwx—— 1 rjc rjc 64 Feb 27 15:32 2 -> /dev/pts/5

Now run GDB:

$ gdb -p 6760 /bin/cat
GNU gdb 6.4.90-debian

[license stuff snipped]

Attaching to program: /bin/cat, process 6760

[snip other stuff that's not interesting now]

(gdb) p close(1)
$1 = 0
(gdb) p creat("/tmp/foo3", 0600)
$2 = 1
(gdb) q
The program is running. Quit anyway (and detach it)? (y or n) y
Detaching from program: /bin/cat, process 6760

The p command in GDB will print the value of an expression, an expression can be a function to call, it can be a system call… So I execute a close() system call and pass file handle 1, then I execute a creat() system call to open a new file. The result of the creat() was 1 which means that it replaced the previous file handle. If I wanted to use the same file for stdout and stderr or if I wanted to replace a file handle with some other number then I would need to call the dup2() system call to achieve that result.

For this example I chose to use creat() instead of open() because there are fewer parameter. The C macros for the flags are not usable from GDB (it doesn’t use C headers) so I would have to read header files to discover this – it’s not that hard to do so but would take more time. Note that 0600 is the octal permission for the owner having read/write access and the group and others having no access. It would also work to use 0 for that parameter and run chmod on the file later on.

After that I verify the result:

ls -l /proc/6760/fd/
total 3
lrwx—— 1 rjc rjc 64 2008-02-27 15:32 0 -> /dev/pts/5
l-wx—— 1 rjc rjc 64 2008-02-27 15:32 1 -> /tmp/foo3 <====
lrwx—— 1 rjc rjc 64 2008-02-27 15:32 2 -> /dev/pts/5

Typing more data in to cat results in the file /tmp/foo3 being appended to.

If you want to close the original session you need to close all file handles for it, open a new device that can be the controlling tty, and then call setsid().

How to return the output of stored procedure into a variable in sql server

Use this code, Working properly

CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT

AS
Begin
 DECLARE @cnt int;
 DECLARE @status int =0;
 SET NOCOUNT OFF
 SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
 if(@cnt = 1)
   Begin
     return @status;
   End
 else
  Begin
   SET @status =1;
    return @status;
 End
END

Execute SP

DECLARE @statuss bit;
EXECUTE  [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;

Converting integer to digit list

There are already great methods already mentioned on this page, however it does seem a little obscure as to which to use. So I have added some mesurements so you can more easily decide for yourself:


A large number has been used (for overhead) 1111111111111122222222222222222333333333333333333333

Using map(int, str(num)):

import timeit

def method():
    num = 1111111111111122222222222222222333333333333333333333
    return map(int, str(num))

print(timeit.timeit("method()", setup="from __main__ import method", number=10000)

Output: 0.018631496999999997

Using list comprehension:

import timeit

def method():
    num = 1111111111111122222222222222222333333333333333333333
    return [int(x) for x in str(num)]

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.28403817900000006

Code taken from this answer

The results show that the first method involving inbuilt methods is much faster than list comprehension.

The "mathematical way":

import timeit

def method():
    q = 1111111111111122222222222222222333333333333333333333
    ret = []
    while q != 0:
        q, r = divmod(q, 10) # Divide by 10, see the remainder
        ret.insert(0, r) # The remainder is the first to the right digit
    return ret

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.38133582499999996

Code taken from this answer

The list(str(123)) method (does not provide the right output):

import timeit

def method():
    return list(str(1111111111111122222222222222222333333333333333333333))
    
print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.028560138000000013

Code taken from this answer

The answer by Duberly González Molinari:

import timeit

def method():
    n = 1111111111111122222222222222222333333333333333333333
    l = []
    while n != 0:
        l = [n % 10] + l
        n = n // 10
    return l

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.37039988200000007

Code taken from this answer

Remarks:

In all cases the map(int, str(num)) is the fastest method (and is therefore probably the best method to use). List comprehension is the second fastest (but the method using map(int, str(num)) is probably the most desirable of the two.

Those that reinvent the wheel are interesting but are probably not so desirable in real use.

Delete last char of string

There is no "quick-and-dirty" way of doing this. I usually do:

mystring= string.Concat(mystring.Take(mystring.Length-1));

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

from collections import Counter
dict1 = {'a':1, 'b': 2}
dict2 = {'b':10, 'c': 11}
result = dict(Counter(dict1) + Counter(dict2))

This should solve your problem.

Get the current file name in gulp.src()

If you want to use @OverZealous' answer (https://stackoverflow.com/a/21806974/1019307) in Typescript, you need to import instead of require:

import * as debug from 'gulp-debug';

...

    return gulp.src('./examples/*.html')
        .pipe(debug({title: 'example src:'}))
        .pipe(gulp.dest('./build'));

(I also added a title).

How do I run a batch file from my Java Application?

ProcessBuilder is the Java 5/6 way to run external processes.

Node JS Error: ENOENT

"/tmp/test.jpg" is not the correct path – this path starts with / which is the root directory.

In unix, the shortcut to the current directory is .

Try this "./tmp/test.jpg"

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

I'm not sure if anybody has spelled it out exactly this way, but you need to understand the following:

There is no "first" element in a set.

Because, as others have said, sets have no ordering. A set is a mathematical concept that specifically does not include ordering.

Of course, your computer can't really keep a list of stuff that's not ordered in memory. It has to have some ordering. Internally it's an array or a linked list or something. But you don't really know what it is, and it doesn't really have a first element; the element that comes out "first" comes out that way by chance, and might not be first next time. Even if you took steps to "guarantee" a particular first element, it's still coming out by chance, because you just happened to get it right for one particular implementation of a Set; a different implementation might not work that way with what you did. And, in fact, you may not know the implementation you're using as well as you think you do.

People run into this ALL. THE. TIME. with RDBMS systems and don't understand. An RDBMS query returns a set of records. This is the same type of set from mathematics: an unordered collection of items, only in this case the items are records. An RDBMS query result has no guaranteed order at all unless you use the ORDER BY clause, but all the time people assume it does and then trip themselves up some day when the shape of their data or code changes slightly and triggers the query optimizer to work a different way and suddenly the results don't come out in the order they expect. These are typically the people who didn't pay attention in database class (or when reading the documentation or tutorials) when it was explained to them, up front, that query results do not have a guaranteed ordering.

Java Refuses to Start - Could not reserve enough space for object heap

You're using a 32-bit OS, so you're going to be seeing limits on the total size due to that. Other answers have covered this in more detail, so I'll avoid repeating their information.

A behaviour that I noticed with our servers recently is that specifying a maximum heap size with -Xmx while not specifying a minimum heap size with -Xms would lead to Java's server VM immediately attempting to allocate all of the memory needed for the maximum heap size. And sure, if the app gets up to that heap size, that's the amount of memory that you'll need. But the chances are, your apps will be starting out with comparitively small heaps and may require the larger heap at some later point. Additionally specifying the minimum heap size will let you start your app start with a smaller heap and gradually grow that heap.

All of this isn't going to help you increase your maximum heap size, but I figured it might help, so...

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

Sorting objects by property values

javascript has the sort function which can take another function as parameter - that second function is used to compare two elements.

Example:

cars = [

    {
        name: "Honda",
        speed: 80
    },

    {
        name: "BMW",
        speed: 180
    },

    {
        name: "Trabi",
        speed: 40
    },

    {
        name: "Ferrari",
        speed: 200
    }
]


cars.sort(function(a, b) { 
    return a.speed - b.speed;
})

for(var i in cars)
    document.writeln(cars[i].name) // Trabi Honda BMW Ferrari 

ok, from your comment i see that you're using the word 'sort' in a wrong sense. In programming "sort" means "put things in a certain order", not "arrange things in groups". The latter is much simpler - this is just how you "sort" things in the real world

  • make two empty arrays ("boxes")
  • for each object in your list, check if it matches the criteria
  • if yes, put it in the first "box"
  • if no, put it in the second "box"

Can overridden methods differ in return type?

Yes, if they return a subtype. Here's an example:

package com.sandbox;

public class Sandbox {

    private static class Parent {
        public ParentReturnType run() {
            return new ParentReturnType();
        }
    }

    private static class ParentReturnType {

    }

    private static class Child extends Parent {
        @Override
        public ChildReturnType run() {
            return new ChildReturnType();
        }
    }

    private static class ChildReturnType extends ParentReturnType {
    }
}

This code compiles and runs.

Alter user defined type in SQL Server

The simplest way to do this is through Visual Studio's object explorer, which is also supported in the Community edition.

Once you have made a connection to SQL server, browse to the type, right click and select View Code, make your changes to the schema of the user defined type and click update. Visual Studio should show you all of the dependencies for that object and generate scripts to update the type and recompile dependencies.

Remove a child with a specific attribute, in SimpleXML for PHP

There is a way to remove a child element via SimpleXml. The code looks for a element, and does nothing. Otherwise it adds the element to a string. It then writes out the string to a file. Also note that the code saves a backup before overwriting the original file.

$username = $_GET['delete_account'];
echo "DELETING: ".$username;
$xml = simplexml_load_file("users.xml");

$str = "<?xml version=\"1.0\"?>
<users>";
foreach($xml->children() as $child){
  if($child->getName() == "user") {
      if($username == $child['name']) {
        continue;
    } else {
        $str = $str.$child->asXML();
    }
  }
}
$str = $str."
</users>";
echo $str;

$xml->asXML("users_backup.xml");
$myFile = "users.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $str);
fclose($fh);

Changing Placeholder Text Color with Swift

For Swift 4

txtField1.attributedPlaceholder = NSAttributedString(string: "-", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

Javascript to stop HTML5 video playback on modal window close

When you close the video you just need to pause it.

$("#closeSimple").click(function() {
    $("div#simpleModal").removeClass("show");
    $("#videoContainer")[0].pause();
    return false;                   
});

<video id="videoContainer" width="320" height="240" src="Davis_5109iPadFig3.m4v" controls="controls"> </video>

Also, for reference, here's the Opera documentation for scripting video controls.

nodeJs callbacks simple example

var myCallback = function(data) {
  console.log('got data: '+data);
};

var usingItNow = function(callback) {
  callback('get it?');
};

Now open node or browser console and paste the above definitions.

Finally use it with this next line:

usingItNow(myCallback);

With Respect to the Node-Style Error Conventions

Costa asked what this would look like if we were to honor the node error callback conventions.

In this convention, the callback should expect to receive at least one argument, the first argument, as an error. Optionally we will have one or more additional arguments, depending on the context. In this case, the context is our above example.

Here I rewrite our example in this convention.

var myCallback = function(err, data) {
  if (err) throw err; // Check for the error and throw if it exists.
  console.log('got data: '+data); // Otherwise proceed as usual.
};

var usingItNow = function(callback) {
  callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument
};

If we want to simulate an error case, we can define usingItNow like this

var usingItNow = function(callback) {
  var myError = new Error('My custom error!');
  callback(myError, 'get it?'); // I send my error as the first argument.
};

The final usage is exactly the same as in above:

usingItNow(myCallback);

The only difference in behavior would be contingent on which version of usingItNow you've defined: the one that feeds a "truthy value" (an Error object) to the callback for the first argument, or the one that feeds it null for the error argument.

json_encode is returning NULL?

I had the same problem and the solution was to use my own function instead of json_encode()

echo '["' . implode('","', $row) . '"]';

Django optional url parameters

Django > 2.0 version:

The approach is essentially identical with the one given in Yuji 'Tomita' Tomita's Answer. Affected, however, is the syntax:

# URLconf
...

urlpatterns = [
    path(
        'project_config/<product>/',
        views.get_product, 
        name='project_config'
    ),
    path(
        'project_config/<product>/<project_id>/',
        views.get_product,
        name='project_config'
    ),
]


# View (in views.py)
def get_product(request, product, project_id='None'):
    # Output the appropriate product
    ...

Using path() you can also pass extra arguments to a view with the optional argument kwargs that is of type dict. In this case your view would not need a default for the attribute project_id:

    ...
    path(
        'project_config/<product>/',
        views.get_product,
        kwargs={'project_id': None},
        name='project_config'
    ),
    ...

For how this is done in the most recent Django version, see the official docs about URL dispatching.

How to detect a route change in Angular?

@Ludohen answer is great, but in case you don't want to use instanceof use the following

this.router.events.subscribe(event => {
  if(event.constructor.name === "NavigationStart") {
    // do something...
  }
});

with this way you can check the current event name as a string and if the event occurred you can do what you planned your function to do.

Moment.js with ReactJS (ES6)

run npm i moment react-moment --save

you can use this in your component,

import Moment from 'react-moment';

const date = new Date();
<Moment format='MMMM Do YYYY, h:mm:ss a'>{date}</Moment>

will give you sth like this :
enter image description here

Can I nest a <button> element inside an <a> using HTML5?

_x000D_
_x000D_
<a href="index.html">_x000D_
  <button type="button">Submit</button>_x000D_
</a>
_x000D_
_x000D_
_x000D_ Or you can use java script in button as:

_x000D_
_x000D_
<button type="submit" onclick="myFunction()">Submit</button>_x000D_
<script>_x000D_
  function myFunction() {_x000D_
      var w = window.open(file:///E:/Aditya%20panchal/index.html);_x000D_
    }_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to read a specific line using the specific line number from a file in Java?

public String readLine(int line){
        FileReader tempFileReader = null;
        BufferedReader tempBufferedReader = null;
        try { tempFileReader = new FileReader(textFile); 
        tempBufferedReader = new BufferedReader(tempFileReader);
        } catch (Exception e) { }
        String returnStr = "ERROR";
        for(int i = 0; i < line - 1; i++){
            try { tempBufferedReader.readLine(); } catch (Exception e) { }
        }
        try { returnStr = tempBufferedReader.readLine(); }  catch (Exception e) { }

        return returnStr;
    }

Possible cases for Javascript error: "Expected identifier, string or number"

Maybe you've got an object having a method 'constructor' and try to invoke that one.

How can I create and style a div using JavaScript?

_x000D_
_x000D_
var div = document.createElement("div");_x000D_
div.style.width = "100px";_x000D_
div.style.height = "100px";_x000D_
div.style.background = "red";_x000D_
div.style.color = "white";_x000D_
div.innerHTML = "Hello";_x000D_
_x000D_
document.getElementById("main").appendChild(div);
_x000D_
<body>_x000D_
<div id="main"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";

document.getElementById("main").appendChild(div);
OR
document.body.appendChild(div);

Use parent reference instead of document.body.

"Specified argument was out of the range of valid values"

It seems that you are trying to get 5 items out of a collection with 5 items. Looking at your code, it seems you're starting at the second value in your collection at position 1. Collections are zero-based, so you should start with the item at index 0. Try this:

TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[0].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_rate");

Best way to require all files from a directory in ruby?

Instead of concatenating paths like in some answers, I use File.expand_path:

Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
  require file
end

Update:

Instead of using File.dirname you could do the following:

Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
  require file
end

Where .. strips the filename of __FILE__.

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

validate: It validates the schema and makes no changes to the DB.
Assume you have added a new column in the mapping file and perform the insert operation, it will throw an Exception "missing the XYZ column" because the existing schema is different than the object you are going to insert. If you alter the table by adding that new column manually then perform the Insert operation then it will definitely insert all columns along with the new column to the Table. Means it doesn't make any changes/alters the existing schema/table.

update: it alters the existing table in the database when you perform operation. You can add or remove columns with this option of hbm2ddl. But if you are going to add a new column that is 'NOT NULL' then it will ignore adding that particular column to the DB. Because the Table must be empty if you want to add a 'NOT NULL' column to the existing table.

Java: How To Call Non Static Method From Main Method?

You can't call a non-static method from a static method, because the definition of "non-static" means something that is associated with an instance of the class. You don't have an instance of the class in a static context.

jQuery Mobile: document ready vs. page events

While you use .on(), it's basically a live query that you are using.

On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.

The use of live queries is common in forms where we enter data (account or posts or even comments).

How to get the entire document HTML as a string?

I always use

document.getElementsByTagName('html')[0].innerHTML

Probably not the right way but I can understand it when I see it.

What is the command for cut copy paste a file from one directory to other directory

use the xclip which is command line interface to X selections

install

apt-get install xclip

usage

echo "test xclip " > /tmp/test.xclip
xclip -i < /tmp/test.xclip
xclip -o > /tmp/test.xclip.out

cat /tmp/test.xclip.out   # "test xclip"

enjoy.

VBA paste range

This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:

'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Sub CopyLayout(TargetRange As Range, typee As Integer)
    Application.ScreenUpdating = False
        Dim ncolumn As Integer
        Dim nrow As Integer

        SheetLayout.Activate
    If (typee = 1) Then 'is installation
        Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    ElseIf (typee = 2) Then 'is package
        Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    End If

    Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@

    If typee = 1 Then
       nrow = SheetLayout.Range("installationlayout").Rows.Count
       ncolumn = SheetLayout.Range("installationlayout").Columns.Count

       Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    ElseIf typee = 2 Then
       nrow = SheetLayout.Range("PackageLayout").Rows.Count
       ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
       Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    End If
    Range("A1").Select 'Deselect the created table

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
    Dim R As Long, C As Long

    For R = 1 To RowCount
        PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
        If R >= 2 And R < RowCount Then
            PastedTable.Rows(R).Group 'Main group of the table
        End If
        If R = 2 Then
            PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
        ElseIf (R = 4 And typee = 1) Then
            PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
        End If
    Next R

    For C = 1 To ColumnCount
        PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
    Next C
End Function



Sub test ()
    Call CopyLayout(Sheet2.Range("A18"), 2)
end sub

How to prevent a jQuery Ajax request from caching in Internet Explorer?

Cache-Control: no-cache, no-store

These two header values can be combined to get the required effect on both IE and Firefox

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

Angular: conditional class with *ngClass

You should use something ([ngClass] instead of *ngClass) like that:

<ol class="breadcrumb">
  <li [ngClass]="{active: step==='step1'}" (click)="step='step1; '">Step1</li>
  (...)

Closure in Java 7

A closure implementation for Java 5, 6, and 7

http://mseifed.blogspot.se/2012/09/bringing-closures-to-java-5-6-and-7.html

It contains all one could ask for...

How to make a node.js application run permanently?

You could install forever using npm like this:

sudo npm install -g forever

And then start your application with:

forever server.js

Or as a service:

forever start server.js

Forever restarts your app when it crashes or stops for some reason. To restrict restarts to 5 you could use:

forever -m5 server.js

To list all running processes:

forever list

Note the integer in the brackets and use it as following to stop a process:

forever stop 0

Restarting a running process goes:

forever restart 0

If you're working on your application file, you can use the -w parameter to restart automatically whenever your server.js file changes:

forever -w server.js

How to run Linux commands in Java?

You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.

For example, here's a complete program that will showcase how to do it:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class testprog {
    public static void main(String args[]) {
        String s;
        Process p;
        try {
            p = Runtime.getRuntime().exec("ls -aF");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}
    }
}

When compiled and run, it outputs:

line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0

as expected.

You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).

If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.

What are the differences between a HashMap and a Hashtable in Java?

HashMap: An implementation of the Map interface that uses hash codes to index an array. Hashtable: Hi, 1998 called. They want their collections API back.

Seriously though, you're better off staying away from Hashtable altogether. For single-threaded apps, you don't need the extra overhead of synchronisation. For highly concurrent apps, the paranoid synchronisation might lead to starvation, deadlocks, or unnecessary garbage collection pauses. Like Tim Howland pointed out, you might use ConcurrentHashMap instead.

Escape double quotes in Java

For a String constant you have no choice other than escaping via backslash.

Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.

How to run only one unit test class using Gradle

In versions of Gradle prior to 5, the test.single system property can be used to specify a single test.

You can do gradle -Dtest.single=ClassUnderTestTest test if you want to test single class or use regexp like gradle -Dtest.single=ClassName*Test test you can find more examples of filtering classes for tests under this link.

Gradle 5 removed this option, as it was superseded by test filtering using the --tests command line option.

How to overwrite the previous print to stdout in python?

I couldn't get any of the solutions on this page to work for IPython, but a slight variation on @Mike-Desimone's solution did the job: instead of terminating the line with the carriage return, start the line with the carriage return:

for x in range(10):
    print '\r{0}'.format(x),

Additionally, this approach doesn't require the second print statement.

Codesign wants to access key "access" in your keychain, I put in my login password but keeps asking me

I had the same problem: while building iOS release for Flutter project, was asked for keychain password, entered Apple ID password for developer account, no luck. Finally succeeded by entering password for computer I was using (which was an on-line mac server). Hope that helps.

Good tool to visualise database schema?

I like this tool, called simply DbSchema. It's written in Java so it runs on OS X, Windows, or Linux. It's a little clunky, especially when it comes to printing, but from my experience they're all like that. This one is the best of the several I've tried. It makes nice, clear diagrams. Free trial. Costs about $120 depending on how many licenses you buy.

PHP regular expression - filter number only

To remove anything that is not a number:

$output = preg_replace('/[^0-9]/', '', $input);

Explanation:

  • [0-9] matches any number between 0 and 9 inclusively.
  • ^ negates a [] pattern.
  • So, [^0-9] matches anything that is not a number, and since we're using preg_replace, they will be replaced by nothing '' (second argument of preg_replace).

What exactly is LLVM?

LLVM is basically a library used to build compilers and/or language oriented software. The basic gist is although you have gcc which is probably the most common suite of compilers, it is not built to be re-usable ie. it is difficult to take components from gcc and use it to build your own application. LLVM addresses this issue well by building a set of "modular and reusable compiler and toolchain technologies" which anyone could use to build compilers and language oriented software.

Is object empty?

I modified Sean Vieira's code to suit my needs. null and undefined don't count as object at all, and numbers, boolean values and empty strings return false.

_x000D_
_x000D_
'use strict';_x000D_
_x000D_
// Speed up calls to hasOwnProperty_x000D_
var hasOwnProperty = Object.prototype.hasOwnProperty;_x000D_
_x000D_
var isObjectEmpty = function(obj) {_x000D_
    // null and undefined are not empty_x000D_
    if (obj == null) return false;_x000D_
    if(obj === false) return false;_x000D_
    if(obj === true) return false;_x000D_
    if(obj === "") return false;_x000D_
_x000D_
    if(typeof obj === "number") {_x000D_
        return false;_x000D_
    }   _x000D_
    _x000D_
    // Assume if it has a length property with a non-zero value_x000D_
    // that that property is correct._x000D_
    if (obj.length > 0)    return false;_x000D_
    if (obj.length === 0)  return true;_x000D_
_x000D_
    // Otherwise, does it have any properties of its own?_x000D_
    // Note that this doesn't handle_x000D_
    // toString and valueOf enumeration bugs in IE < 9_x000D_
    for (var key in obj) {_x000D_
        if (hasOwnProperty.call(obj, key)) return false;_x000D_
    }_x000D_
    _x000D_
    _x000D_
    _x000D_
    return true;_x000D_
};_x000D_
_x000D_
exports.isObjectEmpty = isObjectEmpty;
_x000D_
_x000D_
_x000D_

How to get elements with multiple classes

html

<h2 class="example example2">A heading with class="example"</h2>

javascritp code

var element = document.querySelectorAll(".example.example2");
element.style.backgroundColor = "green";

The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

also learn more about https://www.w3schools.com/jsref/met_document_queryselectorall.asp

== Thank You ==

phpmyadmin logs out after 1440 secs

Follow below steps to increase session timeout for phpmyadmin:

Method 1:

  • Login to phpMyAdmin with your root credentials
  • Select Settings from the top in navigation bar
  • Tap on Features
  • Search for Login cookie validity field in General tab
  • Change the value for this field to something greater than 1440 like 36000 or anything higher.

Make sure whatever value you are entering in Login cookie validity is in seconds

phpmyadmin increase session timeout

Method 2:

Locate your config.inc.php file

For CentOS, Fedora servers:
/etc/phpMyAdmin/config.inc.php

For Ubuntu, Debian servers:
/etc/phpmyadmin/config.inc.php

Search LoginCookieValidity in config.inc.php and increase its value

$cfg['Servers'] [$i] ['LoginCookieValidity'] = 1440;

//change to 
$cfg['Servers'] [$i] ['LoginCookieValidity'] = 36000;

Save the changes to the config.inc.php file and restart your server.

Increase session.gc_maxlifetime in php.ini to be greater than or equal to the value that you entered in config.inc.php.

m2e lifecycle-mapping not found

The org.eclipse.m2e:lifecycle-mapping plugin doesn't exist actually. It should be used from the <build><pluginManagement> section of your pom.xml. That way, it's not resolved by Maven but can be read by m2e.

But a more practical solution to your problem would be to install the m2e build-helper connector in eclipse. You can install it from the Window > Preferences > Maven > Discovery > Open Catalog. That way build-helper-maven-plugin:add-sources would be called in eclipse without having you to change your pom.xml.

How to write hello world in assembler under Windows?

These are Win32 and Win64 examples using Windows API calls. They are for MASM rather than NASM, but have a look at them. You can find more details in this article.

This uses MessageBox instead of printing to stdout.

Win32 MASM

;---ASM Hello World Win32 MessageBox

.386
.model flat, stdcall
include kernel32.inc
includelib kernel32.lib
include user32.inc
includelib user32.lib

.data
title db 'Win32', 0
msg db 'Hello World', 0

.code

Main:
push 0            ; uType = MB_OK
push offset title ; LPCSTR lpCaption
push offset msg   ; LPCSTR lpText
push 0            ; hWnd = HWND_DESKTOP
call MessageBoxA
push eax          ; uExitCode = MessageBox(...)
call ExitProcess

End Main

Win64 MASM

;---ASM Hello World Win64 MessageBox

extrn MessageBoxA: PROC
extrn ExitProcess: PROC

.data
title db 'Win64', 0
msg db 'Hello World!', 0

.code
main proc
  sub rsp, 28h  
  mov rcx, 0       ; hWnd = HWND_DESKTOP
  lea rdx, msg     ; LPCSTR lpText
  lea r8,  title   ; LPCSTR lpCaption
  mov r9d, 0       ; uType = MB_OK
  call MessageBoxA
  add rsp, 28h  
  mov ecx, eax     ; uExitCode = MessageBox(...)
  call ExitProcess
main endp

End

To assemble and link these using MASM, use this for 32-bit executable:

ml.exe [filename] /link /subsystem:windows 
/defaultlib:kernel32.lib /defaultlib:user32.lib /entry:Main

or this for 64-bit executable:

ml64.exe [filename] /link /subsystem:windows 
/defaultlib:kernel32.lib /defaultlib:user32.lib /entry:main

Why does x64 Windows need to reserve 28h bytes of stack space before a call? That's 32 bytes (0x20) of shadow space aka home space, as required by the calling convention. And another 8 bytes to re-align the stack by 16, because the calling convention requires RSP be 16-byte aligned before a call. (Our main's caller (in the CRT startup code) did that. The 8-byte return address means that RSP is 8 bytes away from a 16-byte boundary on entry to a function.)

Shadow space can be used by a function to dump its register args next to where any stack args (if any) would be. A system call requires 30h (48 bytes) to also reserve space for r10 and r11 in addition to the previously mentioned 4 registers. But DLL calls are just function calls, even if they're wrappers around syscall instructions.

Fun fact: non-Windows, i.e. the x86-64 System V calling convention (e.g. on Linux) doesn't use shadow space at all, and uses up to 6 integer/pointer register args, and up to 8 FP args in XMM registers.


Using MASM's invoke directive (which knows the calling convention), you can use one ifdef to make a version of this which can be built as 32-bit or 64-bit.

ifdef rax
    extrn MessageBoxA: PROC
    extrn ExitProcess: PROC
else
    .386
    .model flat, stdcall
    include kernel32.inc
    includelib kernel32.lib
    include user32.inc
    includelib user32.lib
endif
.data
caption db 'WinAPI', 0
text    db 'Hello World', 0
.code
main proc
    invoke MessageBoxA, 0, offset text, offset caption, 0
    invoke ExitProcess, eax
main endp
end

The macro variant is the same for both, but you won't learn assembly this way. You'll learn C-style asm instead. invoke is for stdcall or fastcall while cinvoke is for cdecl or variable argument fastcall. The assembler knows which to use.

You can disassemble the output to see how invoke expanded.

SQL grouping by month and year

If you want to stay having the field in datetime datatype, try using this:

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada 
FROM [Order] o
WHERE (idCustomer = 1) AND (o.[date] BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0)

It it also easy to change to group by hours, days, weeks, years...
I hope it is of use to someone,

Regards!

jQuery override default validation error message display (Css) Popup/Tooltip like

You can use the errorPlacement option to override the error message display with little css. Because css on its own will not be enough to produce the effect you need.

$(document).ready(function(){
    $("#myForm").validate({
        rules: {
            "elem.1": {
                required: true,
                digits: true
            },
            "elem.2": {
                required: true
            }
        },
        errorElement: "div",
        wrapper: "div",  // a wrapper around the error message
        errorPlacement: function(error, element) {
            offset = element.offset();
            error.insertBefore(element)
            error.addClass('message');  // add a class to the wrapper
            error.css('position', 'absolute');
            error.css('left', offset.left + element.outerWidth());
            error.css('top', offset.top);
        }

    });
});

You can play with the left and top css attributes to show the error message on top, left, right or bottom of the element. For example to show the error on the top:

    errorPlacement: function(error, element) {
        element.before(error);
        offset = element.offset();
        error.css('left', offset.left);
        error.css('top', offset.top - element.outerHeight());
    }

And so on. You can refer to jQuery documentation about css for more options.

Here is the css I used. The result looks exactly like the one you want. With as little CSS as possible:

div.message{
    background: transparent url(msg_arrow.gif) no-repeat scroll left center;
    padding-left: 7px;
}

div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid none;
    border-width: 2px;
    padding: 5px;
}

And here is the background image you need:

alt text
(source: scriptiny.com)

If you want the error message to be displayed after a group of options or fields. Then group all those elements inside one container a 'div' or a 'fieldset'. Add a special class to all of them 'group' for example. And add the following to the begining of the errorPlacement function:

errorPlacement: function(error, element) {
    if (element.hasClass('group')){
        element = element.parent();
    }
    ...// continue as previously explained

If you only want to handle specific cases you can use attr instead:

if (element.attr('type') == 'radio'){
    element = element.parent();
}

That should be enough for the error message to be displayed next to the parent element.

You may need to change the width of the parent element to be less than 100%.


I've tried your code and it is working perfectly fine for me. Here is a preview: alt text

I just made a very small adjustment to the message padding to make it fit in the line:

div.error {
    padding: 2px 5px;
}

You can change those numbers to increase/decrease the padding on top/bottom or left/right. You can also add a height and width to the error message. If you are still having issues, try to replace the span with a div

<div class="group">
<input type="radio" class="checkbox" value="P" id="radio_P" name="radio_group_name"/>
<label for="radio_P">P</label>
<input type="radio" class="checkbox" value="S" id="radio_S" name="radio_group_name"/>
<label for="radio_S">S</label>
</div>

And then give the container a width (this is very important)

div.group {
    width: 50px; /* or any other value */
}

About the blank page. As I said I tried your code and it is working for me. It might be something else in your code that is causing the issue.

Debug/run standard java in Visual Studio Code IDE and OS X?

There is a much easier way to run Java, no configuration needed:

  1. Install the Code Runner Extension
  2. Open your Java code file in Text Editor, then use shortcut Ctrl+Alt+N, or press F1 and then select/type Run Code, or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.

runJave

WPF Binding StringFormat Short Date String

Be aware of the single quotes for the string format. This doesn't work:

    Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"

while this does:

    Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"

Why doesn't git recognize that my file has been changed, therefore git add not working

Like it was already discussed, the files were probably flagged with "assume-unchanged", which basicly tells git that you will not modify the files, so it doesnt need to track changes with them. However this may be affecting multiple files, and if its a large workspace you might not want to check them all one by one. In that case you can try: git update-index --really-refresh

according to the docs:

Like --refresh, but checks stat information unconditionally, without regard to the "assume unchanged" setting.

It will basicly force git to track changes of all files regardless of the "assume-unchanged" flags.

javascript change background color on click

You can sets the body's background colour using document.body.style.backgroundColor = "red"; so this can be put into a function that's called when the user clicks. The next part can be done by using document.getElementByID("divID").style.backgroundColor = "red"; window.setTimeout("yourFunction()",10000); which calls yourFunction in 10 seconds to change the colour back.

Handling InterruptedException in Java

What is the difference between the following ways of handling InterruptedException? What is the best way to do it?

You've probably come to ask this question because you've called a method that throws InterruptedException.

First of all, you should see throws InterruptedException for what it is: A part of the method signature and a possible outcome of calling the method you're calling. So start by embracing the fact that an InterruptedException is a perfectly valid result of the method call.

Now, if the method you're calling throws such exception, what should your method do? You can figure out the answer by thinking about the following:

Does it make sense for the method you are implementing to throw an InterruptedException? Put differently, is an InterruptedException a sensible outcome when calling your method?

  • If yes, then throws InterruptedException should be part of your method signature, and you should let the exception propagate (i.e. don't catch it at all).

    Example: Your method waits for a value from the network to finish the computation and return a result. If the blocking network call throws an InterruptedException your method can not finish computation in a normal way. You let the InterruptedException propagate.

    int computeSum(Server server) throws InterruptedException {
        // Any InterruptedException thrown below is propagated
        int a = server.getValueA();
        int b = server.getValueB();
        return a + b;
    }
    
  • If no, then you should not declare your method with throws InterruptedException and you should (must!) catch the exception. Now two things are important to keep in mind in this situation:

    1. Someone interrupted your thread. That someone is probably eager to cancel the operation, terminate the program gracefully, or whatever. You should be polite to that someone and return from your method without further ado.

    2. Even though your method can manage to produce a sensible return value in case of an InterruptedException the fact that the thread has been interrupted may still be of importance. In particular, the code that calls your method may be interested in whether an interruption occurred during execution of your method. You should therefore log the fact an interruption took place by setting the interrupted flag: Thread.currentThread().interrupt()

    Example: The user has asked to print a sum of two values. Printing "Failed to compute sum" is acceptable if the sum can't be computed (and much better than letting the program crash with a stack trace due to an InterruptedException). In other words, it does not make sense to declare this method with throws InterruptedException.

    void printSum(Server server) {
         try {
             int sum = computeSum(server);
             System.out.println("Sum: " + sum);
         } catch (InterruptedException e) {
             Thread.currentThread().interrupt();  // set interrupt flag
             System.out.println("Failed to compute sum");
         }
    }
    

By now it should be clear that just doing throw new RuntimeException(e) is a bad idea. It isn't very polite to the caller. You could invent a new runtime exception but the root cause (someone wants the thread to stop execution) might get lost.

Other examples:

Implementing Runnable: As you may have discovered, the signature of Runnable.run does not allow for rethrowing InterruptedExceptions. Well, you signed up on implementing Runnable, which means that you signed up to deal with possible InterruptedExceptions. Either choose a different interface, such as Callable, or follow the second approach above.

 

Calling Thread.sleep: You're attempting to read a file and the spec says you should try 10 times with 1 second in between. You call Thread.sleep(1000). So, you need to deal with InterruptedException. For a method such as tryToReadFile it makes perfect sense to say, "If I'm interrupted, I can't complete my action of trying to read the file". In other words, it makes perfect sense for the method to throw InterruptedExceptions.

String tryToReadFile(File f) throws InterruptedException {
    for (int i = 0; i < 10; i++) {
        if (f.exists())
            return readFile(f);
        Thread.sleep(1000);
    }
    return null;
}

This post has been rewritten as an article here.

Owl Carousel, making custom navigation

You can use a JS and SCSS/Fontawesome combination for the Prev/Next buttons.

In your JS (this includes screenreader only/accessibility classes with Zurb Foundation):

$('.whatever-carousel').owlCarousel({
    ... ...
    navText: ["<span class='show-for-sr'>Previous</span>","<span class='show-for-sr'>Next</span>"]
    ... ...
})

In your SCSS this:

.owl-theme {

    .owl-nav {
        .owl-prev,
        .owl-next {
            font-family: FontAwesome;
            //border-radius: 50%;
            //padding: whatever-to-get-a-circle;
            transition: all, .2s, ease;
        }
        .owl-prev {
            &::before {
                content: "\f104";
            }
        }
        .owl-next {
            &::before {
                content: "\f105";
            }
        }
    }
}

For the FontAwesome font-family I happen to use the embed code in the document header:

<script src="//use.fontawesome.com/123456whatever.js"></script>

There are various ways to include FA, strokes/folks, but I find this is pretty fast and as I'm using webpack I can just about live with that 1 extra js server call.

And to update this - there's also this JS option for slightly more complex arrows, still with accessibility in mind:

$('.whatever-carousel').owlCarousel({
    navText: ["<span class=\"fa-stack fa-lg\" aria-hidden=\"true\"><span class=\"show-for-sr\">Previous</span><i class=\"fa fa-circle fa-stack-2x\"></i><i class=\"fa fa-chevron-left fa-stack-1x fa-inverse\" aria-hidden=\"true\"></i></span>","<span class=\"fa-stack fa-lg\" aria-hidden=\"true\"><span class=\"show-for-sr\">Next</span><i class=\"fa fa-circle fa-stack-2x\"></i><i class=\"fa fa-chevron-right fa-stack-1x fa-inverse\" aria-hidden=\"true\"></i></span>"]
})

Loads of escaping there, use single quotes instead if preferred.

And in the SCSS just comment out the ::before attrs:

.owl-prev {
        //&::before { content: "\f104"; }
    }
    .owl-next {
        //&::before { content: "\f105"; }
    }

pip install from git repo branch

Prepend the url prefix git+ (See VCS Support):

pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6

And specify the branch name without the leading /.

Double value to round up in Java

You could try defining a new DecimalFormat and using it as a Double result to a new double variable.

Example given to make you understand what I just said.

double decimalnumber = 100.2397;
DecimalFormat dnf = new DecimalFormat( "#,###,###,##0.00" );
double roundednumber = new Double(dnf.format(decimalnumber)).doubleValue();

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

Here is a shorter bit of code that reenables scroll bars across your entire website. I'm not sure if it's much different than the current most popular answer but here it is:

::-webkit-scrollbar {
    -webkit-appearance: none;
    width: 7px;
}
::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background-color: rgba(0,0,0,.5);
    box-shadow: 0 0 1px rgba(255,255,255,.5);
}

Found at this link: http://simurai.com/blog/2011/07/26/webkit-scrollbar

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

This error occurred when you are putting JPA dependencies in your spring-boot configuration file like in maven or gradle. The solution is: Spring-Boot Documentation

You have to specify the DB connection string and driver details in application.properties file. This will solve the issue. This might help to someone.

Applying CSS styles to all elements inside a DIV

#applyCSS > * {
  /* Your style */
}

Check this JSfiddle

It will style all children and grandchildren, but will exclude loosely flying text in the div itself and only target wrapped (by tags) content.

Styling a disabled input with css only

Let's just say you have 3 buttons:

<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">

To style the disabled button you can use the following css:

input[type="button"]:disabled{
    color:#000;
}

This will only affect the button which is disabled.

To stop the color changing when hovering you can use this too:

input[type="button"]:disabled:hover{
    color:#000;
}

You can also avoid this by using a css-reset.

DECODE( ) function in SQL Server

Just for completeness (because nobody else posted the most obvious answer):

Oracle:

DECODE(PC_SL_LDGR_CODE, '02', 'DR', 'CR')

MSSQL (2012+):

IIF(PC_SL_LDGR_CODE='02', 'DR', 'CR')

The bad news:

DECODE with more than 4 arguments would result in an ugly IIF cascade

Angular2: How to load data before rendering the component?

You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.

There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.

Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.

enter image description here

Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:

import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';

@Injectable()
export class MyResolver implements Resolve<MyData> {
  constructor(private ms: MyService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
    let id = route.params['id'];

    return this.ms.getId(id).then(data => {
      if (data) {
        return data;
      } else {
        this.router.navigate(['/login']);
        return;
      }
    });
  }
}

and in the module:

import { MyResolver } from './my-resolver.service';

@NgModule({
  imports: [
    RouterModule.forChild(myRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
    MyResolver
  ]
})
export class MyModule { }

and you can access it in your Component like this:

/////
 ngOnInit() {
    this.route.data
      .subscribe((data: { mydata: myData }) => {
        this.id = data.mydata.id;
      });
  }
/////

And in the Route something like this (usually in the app.routing.ts file):

////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

Check your js files actually exist on the server. I had this problem and discovered the js files hadn't been uploaded to the server and the server was actually returning the html page instead - which was the default document configured on the server (eg default.html)

Setting a max height on a table

<table  style="border: 1px solid red">
            <thead>
                <tr>
                    <td>Header stays put, no scrolling</td>
                </tr>
            </thead>
            <tbody id="tbodyMain" style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
                <tr>
                    <td>cell 1/1</td>
                    <td>cell 1/2</td>
                </tr>
                <tr>
                    <td>cell 2/1</td>
                    <td>cell 2/2</td>
                </tr>
                <tr>
                    <td>cell 3/1</td>
                    <td>cell 3/2</td>
                </tr>
            </tbody>
        </table>


Javascript Section

<script>
$(document).ready(function(){
   var maxHeight = Math.max.apply(null, $("body").map(function () { return $(this).height(); }).get());
   // alert(maxHeight);
    var borderheight =3 ; 
    // Added some pixed into maxheight 
    // If you set border then need to add this "borderheight" to maxheight varialbe
   $("#tbodyMain").css("min-height", parseInt(maxHeight + borderheight) + "px");             
});

</script>


please, refer How to set maximum possible height to your Table Body
Fiddle Here

Is there a way to create key-value pairs in Bash script?

In bash version 4 associative arrays were introduced.

declare -A arr

arr["key1"]=val1

arr+=( ["key2"]=val2 ["key3"]=val3 )

The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.

for key in ${!arr[@]}; do
    echo ${key} ${arr[${key}]}
done

Will loop over all key values and echo them out.

Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

Passing command line arguments to R CMD BATCH

I add an answer because I think a one line solution is always good! Atop of your myRscript.R file, add the following line:

eval(parse(text=paste(commandArgs(trailingOnly = TRUE), collapse=";")))

Then submit your script with something like:

R CMD BATCH [options] '--args arguments you want to supply' myRscript.R &

For example:

R CMD BATCH --vanilla '--args N=1 l=list(a=2, b="test") name="aname"' myscript.R &

Then:

> ls()
[1] "N"    "l"    "name"

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

ConcurrentHashMap was presented as alternative to Hashtable in Java 1.5 as part of concurrency package. With ConcurrentHashMap, you have a better choice not only if it can be safely used in the concurrent multi-threaded environment but also provides better performance than Hashtable and synchronizedMap. ConcurrentHashMap performs better because it locks a part of Map. It allows concurred read operations and the same time maintains integrity by synchronizing write operations.

How ConcurrentHashMap is implemented

ConcurrentHashMap was developed as alternative of Hashtable and support all functionality of Hashtable with additional ability, so called concurrency level. ConcurrentHashMap allows multiple readers to read simultaneously without using blocks. It becomes possible by separating Map to different parts and blocking only part of Map in updates. By default, concurrency level is 16, so Map is spitted to 16 parts and each part is managed by separated block. It means, that 16 threads can work with Map simultaneously, if they work with different parts of Map. It makes ConcurrentHashMap hight productive, and not to down thread-safety.

If you are interested in some important features of ConcurrentHashMap and when you should use this realization of Map - I just put a link to a good article - How to use ConcurrentHashMap in Java

Get characters after last / in url

You could explode based on "/", and return the last entry:

print end( explode( "/", "http://www.vimeo.com/1234567" ) );

That's based on blowing the string apart, something that isn't necessary if you know the pattern of the string itself will not soon be changing. You could, alternatively, use a regular expression to locate that value at the end of the string:

$url = "http://www.vimeo.com/1234567";

if ( preg_match( "/\d+$/", $url, $matches ) ) {
    print $matches[0];
}

Differences between Ant and Maven

Maven is a Framework, Ant is a Toolbox

Maven is a pre-built road car, whereas Ant is a set of car parts. With Ant you have to build your own car, but at least if you need to do any off-road driving you can build the right type of car.

To put it another way, Maven is a framework whereas Ant is a toolbox. If you're content with working within the bounds of the framework then Maven will do just fine. The problem for me was that I kept bumping into the bounds of the framework and it wouldn't let me out.

XML Verbosity

tobrien is a guy who knows a lot about Maven and I think he provided a very good, honest comparison of the two products. He compared a simple Maven pom.xml with a simple Ant build file and he made mention of how Maven projects can become more complex. I think that its worth taking a look at a comparison of a couple of files that you are more likely to see in a simple real-world project. The files below represent a single module in a multi-module build.

First, the Maven file:

<project 
    xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-4_0_0.xsd">

    <parent>
        <groupId>com.mycompany</groupId>
        <artifactId>app-parent</artifactId>
        <version>1.0</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>persist</artifactId>
    <name>Persistence Layer</name>

    <dependencies>

        <dependency>
            <groupId>com.mycompany</groupId>
            <artifactId>common</artifactId>
            <scope>compile</scope>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>com.mycompany</groupId>
            <artifactId>domain</artifactId>
            <scope>provided</scope>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>${hibernate.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>${commons-lang.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
            <version>${spring.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.dbunit</groupId>
            <artifactId>dbunit</artifactId>
            <version>2.2.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
            <classifier>jdk15</classifier>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${commons-dbcp.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc</artifactId>
            <version>${oracle-jdbc.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>${easymock.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

And the equivalent Ant file:

<project name="persist" >

    <import file="../build/common-build.xml" />


    <path id="compile.classpath.main">
        <pathelement location="${common.jar}" />
        <pathelement location="${domain.jar}" />
        <pathelement location="${hibernate.jar}" />
        <pathelement location="${commons-lang.jar}" />
        <pathelement location="${spring.jar}" />
    </path>


    <path id="compile.classpath.test">
        <pathelement location="${classes.dir.main}" />
        <pathelement location="${testng.jar}" />
        <pathelement location="${dbunit.jar}" />
        <pathelement location="${easymock.jar}" />
        <pathelement location="${commons-dbcp.jar}" />
        <pathelement location="${oracle-jdbc.jar}" />
        <path refid="compile.classpath.main" />
    </path>


    <path id="runtime.classpath.test">
        <pathelement location="${classes.dir.test}" />
        <path refid="compile.classpath.test" />
    </path>


</project>

tobrien used his example to show that Maven has built-in conventions but that doesn't necessarily mean that you end up writing less XML. I have found the opposite to be true. The pom.xml is 3 times longer than the build.xml and that is without straying from the conventions. In fact, my Maven example is shown without an extra 54 lines that were required to configure plugins. That pom.xml is for a simple project. The XML really starts to grow significantly when you start adding in extra requirements, which is not out of the ordinary for many projects.

But you have to tell Ant what to do

My Ant example above is not complete of course. We still have to define the targets used to clean, compile, test etc. These are defined in a common build file that is imported by all modules in the multi-module project. Which leads me to the point about how all this stuff has to be explicitly written in Ant whereas it is declarative in Maven.

Its true, it would save me time if I didn't have to explicitly write these Ant targets. But how much time? The common build file I use now is one that I wrote 5 years ago with only slight refinements since then. After my 2 year experiment with Maven, I pulled the old Ant build file out of the closet, dusted it off and put it back to work. For me, the cost of having to explicitly tell Ant what to do has added up to less than a week over a period of 5 years.

Complexity

The next major difference I'd like to mention is that of complexity and the real-world effect it has. Maven was built with the intention of reducing the workload of developers tasked with creating and managing build processes. In order to do this it has to be complex. Unfortunately that complexity tends to negate their intended goal.

When compared with Ant, the build guy on a Maven project will spend more time:

  • Reading documentation: There is much more documentation on Maven, because there is so much more you need to learn.
  • Educating team members: They find it easier to ask someone who knows rather than trying to find answers themselves.
  • Troubleshooting the build: Maven is less reliable than Ant, especially the non-core plugins. Also, Maven builds are not repeatable. If you depend on a SNAPSHOT version of a plugin, which is very likely, your build can break without you having changed anything.
  • Writing Maven plugins: Plugins are usually written with a specific task in mind, e.g. create a webstart bundle, which makes it more difficult to reuse them for other tasks or to combine them to achieve a goal. So you may have to write one of your own to workaround gaps in the existing plugin set.

In contrast:

  • Ant documentation is concise, comprehensive and all in one place.
  • Ant is simple. A new developer trying to learn Ant only needs to understand a few simple concepts (targets, tasks, dependencies, properties) in order to be able to figure out the rest of what they need to know.
  • Ant is reliable. There haven't been very many releases of Ant over the last few years because it already works.
  • Ant builds are repeatable because they are generally created without any external dependencies, such as online repositories, experimental third-party plugins etc.
  • Ant is comprehensive. Because it is a toolbox, you can combine the tools to perform almost any task you want. If you ever need to write your own custom task, it's very simple to do.

Familiarity

Another difference is that of familiarity. New developers always require time to get up to speed. Familiarity with existing products helps in that regard and Maven supporters rightly claim that this is a benefit of Maven. Of course, the flexibility of Ant means that you can create whatever conventions you like. So the convention I use is to put my source files in a directory name src/main/java. My compiled classes go into a directory named target/classes. Sounds familiar doesn't it.

I like the directory structure used by Maven. I think it makes sense. Also their build lifecycle. So I use the same conventions in my Ant builds. Not just because it makes sense but because it will be familiar to anyone who has used Maven before.

Simplest way to read json from a URL in java

I have done the json parser in simplest way, here it is

package com.inzane.shoapp.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
            System.out.println(line);
        }
        is.close();
        json = sb.toString();

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        System.out.println("error on parse data in jsonparser.java");
    }

    // return JSON String
    return jObj;

}
}

this class returns the json object from the url

and when you want the json object you just call this class and the method in your Activity class

my code is here

String url = "your url";
JSONParser jsonParser = new JSONParser();
JSONObject object = jsonParser.getJSONFromUrl(url);
String content=object.getString("json key");

here the "json key" is denoted that the key in your json file

this is a simple json file example

{
    "json":"hi"
}

Here "json" is key and "hi" is value

This will get your json value to string content.

How to float a div over Google Maps?

Try this:

<style>
   #wrapper { position: relative; }
   #over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }
</style>

<div id="wrapper">
   <div id="google_map">

   </div>

   <div id="over_map">

   </div>
</div>

How to convert minutes to hours/minutes and add various time values together using jQuery?

var timeConvert = function(n){
 var minutes = n%60
 var hours = (n - minutes) / 60
 console.log(hours + ":" + minutes)
}
timeConvert(65)

this will log 1:5 to the console. It is a short and simple solution that should be easy to understand and no jquery plugin is necessary...

Iterate through a C++ Vector using a 'for' loop

There's a couple of strong reasons to use iterators, some of which are mentioned here:

Switching containers later doesn't invalidate your code.

i.e., if you go from a std::vector to a std::list, or std::set, you can't use numerical indices to get at your contained value. Using an iterator is still valid.

Runtime catching of invalid iteration

If you modify your container in the middle of your loop, the next time you use your iterator it will throw an invalid iterator exception.

Hide div by default and show it on click with bootstrap

I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse class to show/hide divs and Bootstrap's "Collapse Event".

What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div> based on, lets say, menu buttons on a navbar. Below is a simple solution to this. The anchor tags (<a>) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-

All that the JavaScript does is makes all the other <div> hide using

$(".main-container.collapse").not($(this)).collapse('hide');

when the loaded <div> is displayed by checking the Collapse event shown.bs.collapse. Here's the Bootstrap documentation on Collapse Event.

Note: main-container is just a custom class.

Here it goes-

_x000D_
_x000D_
$(".main-container.collapse").on('shown.bs.collapse', function () {    _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
       $(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
    This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
    This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I create an object and add attributes to it?

Try the code below:

$ python
>>> class Container(object):
...     pass 
...
>>> x = Container()
>>> x.a = 10
>>> x.b = 20
>>> x.banana = 100
>>> x.a, x.b, x.banana
(10, 20, 100)
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', 
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',     '__sizeof__', 
'__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'banana']

Enter key press behaves like a Tab in Javascript

You could programatically iterate the form elements adding the onkeydown handler as you go. This way you can reuse the code.

In Gradle, is there a better way to get Environment Variables?

I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:

home = System.getenv('HOME')

It helps to keep in mind that anything that works in pure Java will work in Gradle too.

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

That is because is does not exist, since it is bounded to Windows.

Use the standard functions from <stdio.h> instead, such as getc

The suggested ncurses library is good if you want to write console-based GUIs, but I don't think it is what you want.

Java - Get a list of all Classes loaded in the JVM

One way if you already know the package top level path is to use OpenPojo

final List<PojoClass> pojoClasses = PojoClassFactory.getPojoClassesRecursively("my.package.path", null);

Then you can go over the list and perform any functionality you desire.

How to clear jQuery validation error messages?

Write own code because everyone uses a different class name. I am resetting jQuery validation by this code.

$('.error').remove();
        $('.is-invalid').removeClass('is-invalid');

How to print the full NumPy array, without truncation?

with np.printoptions(edgeitems=50):
    print(x)

Change 50 to how many lines you wanna see

Source: here

Replace all double quotes within String

This is to remove double quotes in a string.

str1 = str.replace(/"/g, "");
alert(str1);

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
<song> 
 <heading>
 The Twelve Days of Christmas
 </heading>
 ....
</song>

The error about well-formed XML on the root level should disappear (though there may be other issues).

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

TypeError: 'module' object is not callable

check the import statements since a module is not callable. In Python, everything (including functions, methods, modules, classes etc.) is an object.

How can I check which version of Angular I'm using?

On your project folder, open the command terminal and type

ng -v

it will give you a list of items, in that you will be able to see the angular version. See the screenshot.

version details

Verify object attribute value with mockito

New feature added to Mockito makes this even easier,

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());

Take a look at Mockito documentation


In case when there are more than one parameters, and capturing of only single param is desired, use other ArgumentMatchers to wrap the rest of the arguments:

verify(mock).doSomething(eq(someValue), eq(someOtherValue), argument.capture());
assertEquals("John", argument.getValue().getName());

How to open the command prompt and insert commands using Java?

I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.

rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");

Java FileWriter how to write to next Line

I'm not sure if I understood correctly, but is this what you mean?

out.write("this is line 1");
out.newLine();
out.write("this is line 2");
out.newLine();
...

How does the vim "write with sudo" trick work?

This also works well:

:w !sudo sh -c "cat > %"

This is inspired by the comment of @Nathan Long.

NOTICE:

" must be used instead of ' because we want % to be expanded before passing to shell.

Remove duplicates from a dataframe in PySpark

if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

count before dedupe:

df.count()

do the de-dupe (convert the column you are de-duping to string type):

from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))

df.drop_duplicates(subset=['colName']).count()

can use a sorted groupby to check to see that duplicates have been removed:

df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)

How to declare a structure in a header that is to be used by multiple files in c?

a.h:

#ifndef A_H
#define A_H

struct a { 
    int i;
    struct b {
        int j;
    }
};

#endif

there you go, now you just need to include a.h to the files where you want to use this structure.

Where is Maven Installed on Ubuntu

Ubuntu 11.10 doesn't have maven3 in repo.

Follow below step to install maven3 on ubuntu 11.10

sudo add-apt-repository ppa:natecarlson/maven3
sudo apt-get update && sudo apt-get install maven3

Open terminal: mvn3 -v

if you want mvn as a binary then execute below script:

sudo ln -s /usr/bin/mvn3 /usr/bin/mvn

I hope this will help you.

Thanks, Rajam

How to preview git-pull without doing fetch?

I use these two commands and I can see the files to change.

  1. First executing git fetch, it gives output like this (part of output):

    ...
    72f8433..c8af041  develop -> origin/develop
    ...

This operation gives us two commit IDs, first is the old one, and second will be the new.

  1. Then compare these two commits using git diff

    git diff 72f8433..c8af041 | grep "diff --git"

This command will list the files that will be updated:

diff --git a/app/controller/xxxx.php b/app/controller/xxxx.php
diff --git a/app/view/yyyy.php b/app/view/yyyy.php

For example app/controller/xxxx.php and app/view/yyyy.php will be updated.

Comparing two commits using git diff prints all updated files with changed lines, but with grep it searches and gets only the lines contains diff --git from output.

How to "Open" and "Save" using java

You want to use a JFileChooser object. It will open and be modal, and block in the thread that opened it until you choose a file.

Open:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // load from file
}

Save:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // save to file
}

There are more options you can set to set the file name extension filter, or the current directory. See the API for the javax.swing.JFileChooser for details. There is also a page for "How to Use File Choosers" on Oracle's site:

http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Unsuccessful append to an empty NumPy array

I might understand the question incorrectly, but if you want to declare an array of a certain shape but with nothing inside, the following might be helpful:

Initialise empty array:

>>> a = np.zeros((0,3)) #or np.empty((0,3)) or np.array([]).reshape(0,3)
>>> a
array([], shape=(0, 3), dtype=float64)

Now you can use this array to append rows of similar shape to it. Remember that a numpy array is immutable, so a new array is created for each iteration:

>>> for i in range(3):
...     a = np.vstack([a, [i,i,i]])
...
>>> a
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.]])

np.vstack and np.hstack is the most common method for combining numpy arrays, but coming from Matlab I prefer np.r_ and np.c_:

Concatenate 1d:

>>> a = np.zeros(0)
>>> for i in range(3):
...     a = np.r_[a, [i, i, i]]
...
>>> a
array([ 0.,  0.,  0.,  1.,  1.,  1.,  2.,  2.,  2.])

Concatenate rows:

>>> a = np.zeros((0,3))
>>> for i in range(3):
...     a = np.r_[a, [[i,i,i]]]
...
>>> a
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.]])

Concatenate columns:

>>> a = np.zeros((3,0))
>>> for i in range(3):
...     a = np.c_[a, [[i],[i],[i]]]
...
>>> a
array([[ 0.,  1.,  2.],
       [ 0.,  1.,  2.],
       [ 0.,  1.,  2.]])

Adding close button in div to close the box

jQuery("#your_div_id").remove(); will completely remove the corresponding elements from the HTML DOM. So if you want to show the div on another event without a refresh, it will not be possible to retrieve the removed elements back unless you use AJAX.

jQuery("#your_div_id").toggle("slow"); will also could make unexpected results. As an Example when you select some element on your div which generates another div with a close button(which uses the same close functionality just as your previous div) it could make undesired behaviour.

So without using AJAX, a good solution for the close button would be as follows

HTML____________

<div id="your_div_id">
<span class="close_div" onclick="close_div(1)">&#10006</span>
</div>

JQUERY__________

function close_div(id) {
    if(id === 1) {
        jQuery("#your_div_id").hide();
    }
}

Now you can show the div, when another event occures as you wish... :-)

SQL Server NOLOCK and joins

I was pretty sure that you need to specify the NOLOCK for each JOIN in the query. But my experience was limited to SQL Server 2005.

When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:

[SQL Server 2008 R2]

All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

[SQL Server 2005]

In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

Additionally, point to note - and this applies to both 2005 and 2008:

The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the OPTION (EXPAND VIEWS) query hint.

Java error - "invalid method declaration; return type required"

As you can see, the code public Circle(double r).... how is that different from what I did in mine with public CircleR(double r)? For whatever reason, no error is given in the code from the book, however mine says there is an error there.

When defining constructors of a class, they should have the same name as its class. Thus the following code

public class Circle
{ 
    //This part is called the constructor and lets us specify the radius of a  
    //particular circle. 
  public Circle(double r) 
  { 
   radius = r; 
  }
 ....
} 

is correct while your code

public class Circle
{
    private double radius;
    public CircleR(double r)
    {
        radius = r;
    }
    public diameter()
    {
       double d = radius * 2;
       return d;
    }
}

is wrong because your constructor has different name from its class. You could either follow the same code from the book and change your constructor from

public CircleR(double r) 

to

public Circle(double r)

or (if you really wanted to name your constructor as CircleR) rename your class to CircleR.

So your new class should be

public class CircleR
{
    private double radius;
    public CircleR(double r)
    {
        radius = r;
    }
    public double diameter()
    {
       double d = radius * 2;
       return d;
    }
}

I also added the return type double in your method as pointed out by Froyo and John B.

Refer to this article about constructors.

HTH.

Find string between two substrings

Further from Nikolaus Gradwohl answer, I needed to get version number (i.e., 0.0.2) between('ui:' and '-') from below file content (filename: docker-compose.yml):

    version: '3.1'
services:
  ui:
    image: repo-pkg.dev.io:21/website/ui:0.0.2-QA1
    #network_mode: host
    ports:
      - 443:9999
    ulimits:
      nofile:test

and this is how it worked for me (python script):

import re, sys

f = open('docker-compose.yml', 'r')
lines = f.read()
result = re.search('ui:(.*)-', lines)
print result.group(1)


Result:
0.0.2

Dynamically Add Images React Webpack

If you are looking for a way to import all your images from the image

// Import all images in image folder
function importAll(r) {
    let images = {};
    r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
    return images;
}

const images = importAll(require.context('../images', false, /\.(gif|jpe?g|svg)$/));

Then:

<img src={images['image-01.jpg']}/>

You can find the original thread here: Dynamically import images from a directory using webpack

Compare one String with multiple values in one expression

In Java 8+, you might use a Stream<T> and anyMatch(Predicate<? super T>) with something like

if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
    // ...
}

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:

sys.path.insert(1, path_to_dev_pyworkbooks)

This could be important since 3rd party code may rely on sys.path documentation conformance:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

How to create a secure random AES key in Java?

Lots of good advince in the other posts. This is what I use:

Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();

If you need another randomness provider, which I sometime do for testing purposes, just replace rand with

MySecureRandom rand = new MySecureRandom();

AngularJs ReferenceError: $http is not defined

I have gone through the same problem when I was using

    myApp.controller('mainController', ['$scope', function($scope,) {
        //$http was not working in this
    }]);

I have changed the above code to given below. Remember to include $http(2 times) as given below.

 myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
      //$http is working in this
 }]);

and It has worked well.

Check if a String contains numbers Java

Below code snippet will tell whether the String contains digit or not

str.matches(".*\\d.*")
or
str.matches(.*[0-9].*)

For example

String str = "abhinav123";

str.matches(".*\\d.*") or str.matches(.*[0-9].*)  will return true 

str = "abhinav";

str.matches(".*\\d.*") or str.matches(.*[0-9].*)  will return false

How to create strings containing double quotes in Excel formulas?

I use a function for this (if the workbook already has VBA).

Function Quote(inputText As String) As String
  Quote = Chr(34) & inputText & Chr(34)
End Function

This is from Sue Mosher's book "Microsoft Outlook Programming". Then your formula would be:

="Maurice "&Quote("Rocket")&" Richard"

This is similar to what Dave DuPlantis posted.

Searching multiple files for multiple words

If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:

  1. Find What = text1*.*text2
  2. Filters : .
  3. Search mode = Regular Expression
  4. Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

What is pipe() function in Angular

Don't get confused with the concepts of Angular and RxJS

We have pipes concept in Angular and pipe() function in RxJS.

1) Pipes in Angular: A pipe takes in data as input and transforms it to the desired output
https://angular.io/guide/pipes

2) pipe() function in RxJS: You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.

The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
https://angular.io/guide/rx-library (search for pipes in this URL, you can find the same)

So according to your question, you are referring pipe() function in RxJS

Can RDP clients launch remote applications and not desktops

RDP will not do that natively.

As other answers have said -- you'll need to do some scripting and make policy changes as a kludge to make it hard for RDP logins to run anything but the intended application.

However, as of 2008, Microsoft has released application virtualization technology via Terminal Services that will allow you to do this seamlessly.

How do I prevent the padding property from changing width or height in CSS?

If you would like to indent text within a div without changing the size of the div use the CSS text-indent instead of padding-left.

_x000D_
_x000D_
.indent {_x000D_
  text-indent: 1em;_x000D_
}_x000D_
.border {_x000D_
  border-style: solid;_x000D_
}
_x000D_
<div class="border">_x000D_
  Non indented_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<div class="border indent">_x000D_
  Indented_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to determine an interface{} value's "real" type?

There are multiple ways to get a string representation of a type. Switches can also be used with user types:

var user interface{}
user = User{name: "Eugene"}

// .(type) can only be used inside a switch
switch v := user.(type) {
case int:
    // Built-in types are possible (int, float64, string, etc.)
    fmt.Printf("Integer: %v", v)
case User:
    // User defined types work as well  
    fmt.Printf("It's a user: %s\n", user.(User).name)
}

// You can use reflection to get *reflect.rtype
userType := reflect.TypeOf(user)
fmt.Printf("%+v\n", userType)

// You can also use %T to get a string value
fmt.Printf("%T", user)

// You can even get it into a string
userTypeAsString := fmt.Sprintf("%T", user)

if userTypeAsString == "main.User" {
    fmt.Printf("\nIt's definitely a user")
}

Link to a playground: https://play.golang.org/p/VDeNDUd9uK6

How to sign in kubernetes dashboard?

You need to follow these steps before the token authentication

  1. Create a Cluster Admin service account

    kubectl create serviceaccount dashboard -n default
    
  2. Add the cluster binding rules to your dashboard account

    kubectl create clusterrolebinding dashboard-admin -n default --clusterrole=cluster-admin --serviceaccount=default:dashboard
    
  3. Get the secret token with this command

    kubectl get secret $(kubectl get serviceaccount dashboard -o jsonpath="{.secrets[0].name}") -o jsonpath="{.data.token}" | base64 --decode
    
  4. Choose token authentication in the Kubernetes dashboard login page enter image description here

  5. Now you can able to login

JSON formatter in C#?

Shorter sample for json.net library.

using Newtonsoft.Json;

private static string format_json(string json)
{
    dynamic parsedJson = JsonConvert.DeserializeObject(json);
    return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}

PS: You can wrap the formatted json text with tag to print as it is on the html page.

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

How to convert dd/mm/yyyy string into JavaScript Date object?

Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object

    function newUYDate(pDate) {
      let dd = pDate.split("/")[0].padStart(2, "0");
      let mm = pDate.split("/")[1].padStart(2, "0");
      let yyyy = pDate.split("/")[2].split(" ")[0];
      let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
      let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
      let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
    
      mm = (parseInt(mm) - 1).toString(); // January is 0
    
      return new Date(yyyy, mm, dd, hh, mi, secs);
    }

TypeError: string indices must be integers, not str // working with dict

time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

for info in courses[time1][course]:

As you're going through each dictionary, you must add another nest.

Could not find a part of the path ... bin\roslyn\csc.exe

In my case I just needed to go to the bin directory in Visual Studio Solution Explorer (web application project) and include the roslyn project directly. By right clicking the folder and selecting Include In Project. And check in the solution again to trigger the build process.

The roslyn folder was not included by default.

How to echo out the values of this array?

var_dump($value)

it solved my problem, hope yours too.

jQuery: how to get which button was clicked upon form submission?

When the form is submitted:

  • document.activeElement will give you the submit button that was clicked.

  • document.activeElement.getAttribute('value') will give you that button's value.

Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."

Convert ArrayList<String> to String[] array

The correct way to do this is:

String[] stockArr = stock_list.toArray(new String[stock_list.size()]);

I'd like to add to the other great answers here and explain how you could have used the Javadocs to answer your question.

The Javadoc for toArray() (no arguments) is here. As you can see, this method returns an Object[] and not String[] which is an array of the runtime type of your list:

public Object[] toArray()

Returns an array containing all of the elements in this collection. If the collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. The returned array will be "safe" in that no references to it are maintained by the collection. (In other words, this method must allocate a new array even if the collection is backed by an Array). The caller is thus free to modify the returned array.

Right below that method, though, is the Javadoc for toArray(T[] a). As you can see, this method returns a T[] where T is the type of the array you pass in. At first this seems like what you're looking for, but it's unclear exactly why you're passing in an array (are you adding to it, using it for just the type, etc). The documentation makes it clear that the purpose of the passed array is essentially to define the type of array to return (which is exactly your use case):

public <T> T[] toArray(T[] a)

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. If the collection fits in the specified array with room to spare (i.e., the array has more elements than the collection), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the collection only if the caller knows that the collection does not contain any null elements.)

If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

This implementation checks if the array is large enough to contain the collection; if not, it allocates a new array of the correct size and type (using reflection). Then, it iterates over the collection, storing each object reference in the next consecutive element of the array, starting with element 0. If the array is larger than the collection, a null is stored in the first location after the end of the collection.

Of course, an understanding of generics (as described in the other answers) is required to really understand the difference between these two methods. Nevertheless, if you first go to the Javadocs, you will usually find your answer and then see for yourself what else you need to learn (if you really do).

Also note that reading the Javadocs here helps you to understand what the structure of the array you pass in should be. Though it may not really practically matter, you should not pass in an empty array like this:

String [] stockArr = stockList.toArray(new String[0]);  

Because, from the doc, this implementation checks if the array is large enough to contain the collection; if not, it allocates a new array of the correct size and type (using reflection). There's no need for the extra overhead in creating a new array when you could easily pass in the size.

As is usually the case, the Javadocs provide you with a wealth of information and direction.

Hey wait a minute, what's reflection?