Programs & Examples On #Getopt long

Getopt::Long is a command line switch parsing library for Perl. For C-programming: The getopt and getopt_long functions automate some of the chore involved in parsing typical unix command line options.

How to simplify a null-safe compareTo() implementation?

This is my implementation that I use to sort my ArrayList. the null classes are sorted to the last.

for my case, EntityPhone extends EntityAbstract and my container is List < EntityAbstract>.

the "compareIfNull()" method is used for null safe sorting. The other methods are for completeness, showing how compareIfNull can be used.

@Nullable
private static Integer compareIfNull(EntityPhone ep1, EntityPhone ep2) {

    if (ep1 == null || ep2 == null) {
        if (ep1 == ep2) {
            return 0;
        }
        return ep1 == null ? -1 : 1;
    }
    return null;
}

private static final Comparator<EntityAbstract> AbsComparatorByName = = new Comparator<EntityAbstract>() {
    @Override
    public int compare(EntityAbstract ea1, EntityAbstract ea2) {

    //sort type Phone first.
    EntityPhone ep1 = getEntityPhone(ea1);
    EntityPhone ep2 = getEntityPhone(ea2);

    //null compare
    Integer x = compareIfNull(ep1, ep2);
    if (x != null) return x;

    String name1 = ep1.getName().toUpperCase();
    String name2 = ep2.getName().toUpperCase();

    return name1.compareTo(name2);
}
}


private static EntityPhone getEntityPhone(EntityAbstract ea) { 
    return (ea != null && ea.getClass() == EntityPhone.class) ?
            (EntityPhone) ea : null;
}

Visual studio code terminal, how to run a command with administrator rights?

Step 1: Restart VS Code as an adminstrator

(click the windows key, search for "Visual Studio Code", right click, and you'll see the administrator option)

Step 2: In your VS code powershell terminal run Set-ExecutionPolicy Unrestricted

How to take the nth digit of a number in python

First treat the number like a string

number = 9876543210
number = str(number)

Then to get the first digit:

number[0]

The fourth digit:

number[3]

EDIT:

This will return the digit as a character, not as a number. To convert it back use:

int(number[0])

nodejs mysql Error: Connection lost The server closed the connection

Try to use this code to handle server disconnect:

var db_config = {
  host: 'localhost',
    user: 'root',
    password: '',
    database: 'example'
};

var connection;

function handleDisconnect() {
  connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connection.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      handleDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

handleDisconnect();

In your code i am missing the parts after connection = mysql.createConnection(db_config);

Android: Share plain text using intent (to all messaging apps)

Below is the code that works with both the email or messaging app. If you share through email then the subject and body both are added.

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");

                String shareString = Html.fromHtml("Medicine Name:" + medicine_name +
                        "<p>Store Name:" + “store_name “+ "</p>" +
                        "<p>Store Address:" + “store_address” + "</p>")  .toString();
                                      sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Medicine Enquiry");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareString);

                if (sharingIntent.resolveActivity(context.getPackageManager()) != null)
                    context.startActivity(Intent.createChooser(sharingIntent, "Share using"));
                else {
                    Toast.makeText(context, "No app found on your phone which can perform this action", Toast.LENGTH_SHORT).show();
                }

How to create a localhost server to run an AngularJS project

"Assuming that you have nodejs installed",

mini-http is a pretty easy command-line tool to create http server,
install the package globally npm install mini-http -g
then using your cmd (terminal) run mini-http -p=3000 in your project directory And boom! you created a server on port 3000 now go check http://localhost:3000

Note: specifying a port is not required you can simply run mini-http or mh to start the server

Find in Files: Search all code in Team Foundation Server

There is another alternative solution, that seems to be more attractive.

  1. Setup a search server - could be any windows machine/server
  2. Setup a TFS notification service* (Bissubscribe) to get, delete, update files everytime a checkin happens. So this is a web service that acts like a listener on the TFS server, and updates/syncs the files and folders on the Search server. - this will dramatically improve the accuracy (live search), and avoid the one-time load of making periodic gets
  3. Setup an indexing service/windows indexed search on the Search server for the root folder
  4. Expose a web service to return search results

Now with all the above setup, you have a few options for the client:

  1. Setup a web page to call the search service and format the results to show on the webpage - you can also integrate this webpage inside visual studio (through a macro or a add-in)
  2. Create a windows client interface(winforms/wpf) to call the search service and format the results and show them on the UI - you can also integrate this client tool inside visual studio via VSPackages or add-in

Update: I did go this route, and it has been working nicely. Just wanted to add to this.

Reference links:

  1. Use this tool instead of bissubscribe.exe
  2. Handling TFS events
  3. Team System Notifications

How to create a data file for gnuplot?

Create your Datafile like this:

# X      Y
10000.0 0.01
100000.0 0.05
1000000.0 0.45

And plot it with

$ gnuplot -p -e "plot 'filename.dat'"

There is a good tutorial: http://www.gnuplotting.org/introduction/plotting-data/

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

This method will help you to logout from facebook programmatically in android

/**
 * Logout From Facebook 
 */
public static void callFacebookLogout(Context context) {
    Session session = Session.getActiveSession();
    if (session != null) {

        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
            //clear your preferences if saved
        }
    } else {

        session = new Session(context);
        Session.setActiveSession(session);

        session.closeAndClearTokenInformation();
            //clear your preferences if saved

    }

}

500 Internal Server Error for php file not for html

A PHP file must have permissions set to 644. Any folder containing PHP files and PHP access (to upload files, for example) must have permissions set to 755. PHP will run a 500 error when dealing with any file or folder that has permissions set to 777!

program cant start because php5.dll is missing

I had the same problem I switched from wamp to xampp and yes PHP was working because my path was still pointing to my old installation. I had forgotten to change it to point to my new php installation which version of php didn't match the rest at all.

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

How to implement an android:background that doesn't stretch?

The key is to set the drawable as the image of the button, not as a background. Like this:

rb.setButtonDrawable(R.drawable.whatever_drawable);

How to create a bash script to check the SSH connection?

To connect to a server with multiple interfaces

ssh -o ConnectTimeout=1 -q [email protected];[ $? = 1 ] || ssh -o ConnectTimeout=1 -q [email protected]

Assign output of a program to a variable using a MS batch file

One way is:

application arg0 arg1 > temp.txt
set /p VAR=<temp.txt

Another is:

for /f %%i in ('application arg0 arg1') do set VAR=%%i

Note that the first % in %%i is used to escape the % after it and is needed when using the above code in a batch file rather than on the command line. Imagine, your test.bat has something like:

for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i
echo %datetime%

Rounding numbers to 2 digits after comma

I use this:

_x000D_
_x000D_
function round(value, precision) {_x000D_
_x000D_
 if(precision == 0)_x000D_
  return Math.round(value);   _x000D_
_x000D_
 exp = 1;_x000D_
 for(i=0;i<precision;i++)_x000D_
  exp *= 10;_x000D_
_x000D_
 return Math.round(value*exp)/exp;_x000D_
}
_x000D_
_x000D_
_x000D_

How do you pass a function as a parameter in C?

Pass address of a function as parameter to another function as shown below

#include <stdio.h>

void print();
void execute(void());

int main()
{
    execute(print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void f()) // receive address of print
{
    f();
}

Also we can pass function as parameter using function pointer

#include <stdio.h>

void print();
void execute(void (*f)());

int main()
{
    execute(&print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void (*f)()) // receive address of print
{
    f();
}

How do I convert number to string and pass it as argument to Execute Process Task?

Cause of the issue:

Arguments property in Execute Process Task available on the Control Flow tab is expecting a value of data type DT_WSTR and not DT_STR.

SSIS 2008 R2 package illustrating the issue and fix:

Create an SSIS package in Business Intelligence Development Studio (BIDS) 2008 R2 and name it as SO_13177007.dtsx. Create a package variable with the following information.

Name   Scope        Data Type  Value
------ ------------ ---------- -----
IdVar  SO_13177007  Int32      123

Variables pane

Drag and drop an Execute Process Task onto the Control Flow tab and name it as Pass arguments

Control Flow tab

Double-click the Execute Process Task to open the Execute Process Task Editor. Click Expressions page and then click the Ellipsis button against the Expressions property to view the Property Expression Editor.

Execute Process Task Editor

On the Property Expression Editor, select the property Arguments and click the Ellipsis button against the property to open the Expression Builder.

Property Expression Editor

On the Expression Builder, enter the following expression and click Evaluate Expression. This expression tries to convert the integer value in the variable IdVar to string data type.

(DT_STR, 10, 1252) @[User::IdVar]

Expression Builder - DT_STR

Clicking Evaluate Expression will display the following error message because the Arguments property on Execute Process Task expects a value of data type DT_WSTR.

Integer to ANSI string conversion error

To fix the issue, update the expression as shown below to convert the integer value to data type DT_WSTR. Clicking Evaluate Expression will display the value in the Evaluated value text area.

(DT_WSTR, 10) @[User::IdVar]

Expression Builder - DT_WSTR

References:

To understand the differences between the data types DT_STR and DT_WSTR in SSIS, read the documentation Integration Services Data Types on MSDN. Here are the quotes from the documentation about these two string data types.

DT_STR

A null-terminated ANSI/MBCS character string with a maximum length of 8000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)

DT_WSTR

A null-terminated Unicode character string with a maximum length of 4000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)

Differences between Lodash and Underscore.js

I created Lodash to provide more consistent cross-environment iteration support for arrays, strings, objects, and arguments objects1. It has since become a superset of Underscore.js, providing more consistent API behavior, more features (like AMD support, deep clone, and deep merge), more thorough documentation and unit tests (tests which run in Node.js, RingoJS, Rhino, Narwhal, PhantomJS, and browsers), better overall performance and optimizations for large arrays/object iteration, and more flexibility with custom builds and template pre-compilation utilities.

Because Lodash is updated more frequently than Underscore.js, a lodash underscore build is provided to ensure compatibility with the latest stable version of Underscore.js.

At one point I was even given push access to Underscore.js, in part because Lodash is responsible for raising more than 30 issues; landing bug fixes, new features, and performance gains in Underscore.js v1.4.x+.

In addition, there are at least three Backbone.js boilerplates that include Lodash by default and Lodash is now mentioned in Backbone.js’s official documentation.

Check out Kit Cambridge's post, Say "Hello" to Lo-Dash, for a deeper breakdown on the differences between Lodash and Underscore.js.

Footnotes:

  1. Underscore.js has inconsistent support for arrays, strings, objects, and arguments objects. In newer browsers, Underscore.js methods ignore holes in arrays, "Objects" methods iterate arguments objects, strings are treated as array-like, and methods correctly iterate functions (ignoring their "prototype" property) and objects (iterating shadowed properties like "toString" and "valueOf"), while in older browsers they will not. Also, Underscore.js methods, like _.clone, preserve holes in arrays, while others like _.flatten don't.

Regex: match everything but specific pattern

Just match /^index\.php/ then reject whatever matches it.

Java - Search for files in a directory

I have used a different approach to search for a file using stack.. keeping in mind that there could be folders inside a folder. Though its not faster than windows search(and I was not expecting that though) but it definitely gives out correct result. Please modify the code as you wish to. This code was originally made to extract the file path of certain file extension :). Feel free to optimize.

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Deepankar Sinha
 */
public class GetList {
    public List<String> stack;
    static List<String> lnkFile;
    static List<String> progName;

    int index=-1;
    public static void main(String args[]) throws IOException
    {

        //var-- progFile:Location of the file to be search. 
        String progFile="C:\\";
        GetList obj=new GetList();
        String temp=progFile;
        int i;
        while(!"&%@#".equals(temp))
        {
            File dir=new File(temp);
            String[] directory=dir.list();
            if(directory!=null){
            for(String name: directory)
            {
                if(new File(temp+name).isDirectory())
                    obj.push(temp+name+"\\");
                else
                    if(new File(temp+name).isFile())
                    {
                        try{
                            //".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
                        if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
                        {
                            //obj.addFile(temp+name,name);
                            System.out.println(temp+name);
                        }
                        }catch(StringIndexOutOfBoundsException e)
                        {
                            //debug purpose
                            System.out.println("ERROR******"+temp+name);
                        }

                    }
            }}
            temp=obj.pop();
        }
        obj.display();

//        for(int i=0;i<directory.length;i++)
//        System.out.println(directory[i]);
    }

    public GetList() {
        this.stack = new ArrayList<>();
        this.lnkFile=new ArrayList<>();
        this.progName=new ArrayList<>();
    }
    public void push(String dir)
    {
        index++;
        //System.out.println("PUSH : "+dir+" "+index);
        this.stack.add(index,dir);

    }
    public String pop()
    {
        String dir="";
        if(index==-1)
            return "&%@#";
        else
        {
            dir=this.stack.get(index);
            //System.out.println("POP : "+dir+" "+index);
            index--;

        }
        return dir;
    }

    public void addFile(String name,String name2)
    {
        lnkFile.add(name);
        progName.add(name2);
    }

    public void display()
    {
        GetList.lnkFile.stream().forEach((lnkFile1) -> {
            System.out.println(lnkFile1);
        });
    }

}

Portable way to check if directory exists [Windows/Linux, C]

Since I found that the above approved answer lacks some clarity and the op provides an incorrect solution that he/she will use. I therefore hope that the below example will help others. The solution is more or less portable as well.

/******************************************************************************
 * Checks to see if a directory exists. Note: This method only checks the
 * existence of the full path AND if path leaf is a dir.
 *
 * @return  >0 if dir exists AND is a dir,
 *           0 if dir does not exist OR exists but not a dir,
 *          <0 if an error occurred (errno is also set)
 *****************************************************************************/
int dirExists(const char* const path)
{
    struct stat info;

    int statRC = stat( path, &info );
    if( statRC != 0 )
    {
        if (errno == ENOENT)  { return 0; } // something along the path does not exist
        if (errno == ENOTDIR) { return 0; } // something in path prefix is not a dir
        return -1;
    }

    return ( info.st_mode & S_IFDIR ) ? 1 : 0;
}

How to set data attributes in HTML elements

You can also use the following attr thing;

HTML

<div id="mydiv" data-myval="JohnCena"></div>

Script

 $('#mydiv').attr('data-myval', 'Undertaker'); // sets 
 $('#mydiv').attr('data-myval'); // gets

OR

$('#mydiv').data('myval'); // gets value
$('#mydiv').data('myval','John Cena'); // sets value

Add new row to dataframe, at specific row-index, not appended?

Here's a solution that avoids the (often slow) rbind call:

existingDF <- as.data.frame(matrix(seq(20),nrow=5,ncol=4))
r <- 3
newrow <- seq(4)
insertRow <- function(existingDF, newrow, r) {
  existingDF[seq(r+1,nrow(existingDF)+1),] <- existingDF[seq(r,nrow(existingDF)),]
  existingDF[r,] <- newrow
  existingDF
}

> insertRow(existingDF, newrow, r)
  V1 V2 V3 V4
1  1  6 11 16
2  2  7 12 17
3  1  2  3  4
4  3  8 13 18
5  4  9 14 19
6  5 10 15 20

If speed is less important than clarity, then @Simon's solution works well:

existingDF <- rbind(existingDF[1:r,],newrow,existingDF[-(1:r),])
> existingDF
   V1 V2 V3 V4
1   1  6 11 16
2   2  7 12 17
3   3  8 13 18
4   1  2  3  4
41  4  9 14 19
5   5 10 15 20

(Note we index r differently).

And finally, benchmarks:

library(microbenchmark)
microbenchmark(
  rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
  insertRow(existingDF,newrow,r)
)

Unit: microseconds
                                                    expr     min       lq   median       uq       max
1                       insertRow(existingDF, newrow, r) 660.131 678.3675 695.5515 725.2775   928.299
2 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 801.161 831.7730 854.6320 881.6560 10641.417

Benchmarks

As @MatthewDowle always points out to me, benchmarks need to be examined for the scaling as the size of the problem increases. Here we go then:

benchmarkInsertionSolutions <- function(nrow=5,ncol=4) {
  existingDF <- as.data.frame(matrix(seq(nrow*ncol),nrow=nrow,ncol=ncol))
  r <- 3 # Row to insert into
  newrow <- seq(ncol)
  m <- microbenchmark(
   rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
   insertRow(existingDF,newrow,r),
   insertRow2(existingDF,newrow,r)
  )
  # Now return the median times
  mediansBy <- by(m$time,m$expr, FUN=median)
  res <- as.numeric(mediansBy)
  names(res) <- names(mediansBy)
  res
}
nrows <- 5*10^(0:5)
benchmarks <- sapply(nrows,benchmarkInsertionSolutions)
colnames(benchmarks) <- as.character(nrows)
ggplot( melt(benchmarks), aes(x=Var2,y=value,colour=Var1) ) + geom_line() + scale_x_log10() + scale_y_log10()

@Roland's solution scales quite well, even with the call to rbind:

                                                              5       50     500    5000    50000     5e+05
insertRow2(existingDF, newrow, r)                      549861.5 579579.0  789452 2512926 46994560 414790214
insertRow(existingDF, newrow, r)                       895401.0 905318.5 1168201 2603926 39765358 392904851
rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 787218.0 814979.0 1263886 5591880 63351247 829650894

Plotted on a linear scale:

linear

And a log-log scale:

log-log

Python 3 sort a dict by its values

To sort a dictionary and keep it functioning as a dictionary afterwards, you could use OrderedDict from the standard library.

If that's not what you need, then I encourage you to reconsider the sort functions that leave you with a list of tuples. What output did you want, if not an ordered list of key-value pairs (tuples)?

go to character in vim

vim +21490go script.py

From the command line will open the file and take you to position 21490 in the buffer.

Triggering it from the command line like this allows you to automate a script to parse the exception message and open the file to the problem position.


Excerpt from man vim:

+{command}

-c {command}

{command} will be executed after the first file has been read. {command} is interpreted as an Ex command. If the {command} contains spaces it must be enclosed in double quotes (this depends on the shell that is used).

How to remove trailing and leading whitespace for user-provided input in a batch file?

I'd like to present a compact solution using a call by reference (yes, "batch" has pointers too!) to a function, and a "subfunction":

  @ECHO OFF
  SETLOCAL ENABLEDELAYEDEXPANSION

  SET /p NAME=- NAME ? 
  ECHO "%NAME%"
  CALL :TRIM NAME
  ECHO "%NAME%"
  GOTO :EOF

  :TRIM
  SetLocal EnableDelayedExpansion
  Call :TRIMSUB %%%1%%
  EndLocal & set %1=%tempvar%
  GOTO :EOF

  :TRIMSUB
  set tempvar=%*
  GOTO :EOF

How to convert a string variable containing time to time_t type in c++?

With C++11 you can now do

struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);

see std::get_time and strftime for reference

Can I use tcpdump to get HTTP requests, response header and response body?

Here is another choice: Chaosreader

So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...

The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/

It worked like a treat, I did the following:

tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile

Generate random numbers with a given (numerical) distribution

scipy.stats.rv_discrete might be what you want. You can supply your probabilities via the values parameter. You can then use the rvs() method of the distribution object to generate random numbers.

As pointed out by Eugene Pakhomov in the comments, you can also pass a p keyword parameter to numpy.random.choice(), e.g.

numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])

If you are using Python 3.6 or above, you can use random.choices() from the standard library – see the answer by Mark Dickinson.

Android and Facebook share intent

The usual way

The usual way to create what you're asking for, is to simply do the following:

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, "The status update text");
    startActivity(Intent.createChooser(intent, "Dialog title text"));

This works without any issues for me.

The alternative way (maybe)

The potential problem with doing this, is that you're also allowing the message to be sent via e-mail, SMS, etc. The following code is something I'm using in an application, that allows the user to send me an e-mail using Gmail. I'm guessing you could try to change it to make it work with Facebook only.

I'm not sure how it responds to any errors or exceptions (I'm guessing that would occur if Facebook is not installed), so you might have to test it a bit.

    try {
        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        String[] recipients = new String[]{"e-mail address"};
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "E-mail subject");
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "E-mail text");
        emailIntent.setType("plain/text"); // This is incorrect MIME, but Gmail is one of the only apps that responds to it - this might need to be replaced with text/plain for Facebook
        final PackageManager pm = getPackageManager();
        final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
        ResolveInfo best = null;
        for (final ResolveInfo info : matches)
            if (info.activityInfo.packageName.endsWith(".gm") ||
                    info.activityInfo.name.toLowerCase().contains("gmail")) best = info;
                if (best != null)
                    emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
                startActivity(emailIntent);
    } catch (Exception e) {
        Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
    }

Declaring a variable and setting its value from a SELECT query in Oracle

ORA-01422: exact fetch returns more than requested number of rows

if you don't specify the exact record by using where condition, you will get the above exception

DECLARE
     ID NUMBER;
BEGIN
     select eid into id from employee where salary=26500;
     DBMS_OUTPUT.PUT_LINE(ID);
END;

scroll up and down a div on button click using jquery

For the go up, you just need to use scrollTop instead of scrollBottom:

$("#upClick").on("click", function () {
    scrolled = scrolled - 300;
    $(".cover").stop().animate({
        scrollTop: scrolled
    });
});

Also, use the .stop() method to stop the currently-running animation on the cover div. When .stop() is called on an element, the currently-running animation (if any) is immediately stopped.

FIDDLE DEMO

How can I throw CHECKED exceptions from inside Java 8 streams?

Summarizing the comments above the advanced solution is to use a special wrapper for unchecked functions with builder like API which provides recovering, rethrowing and suppresing.

Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
          .map(Try.<String, Class<?>>safe(Class::forName)
                  .handle(System.out::println)
                  .unsafe())
          .collect(toList());

Code below demonstrates it for Consumer, Supplier and Function interfaces. It can be easly expanded. Some public keywords were removed for this example.

Class Try is the endpoint for client code. Safe methods may have unique name for each function type. CheckedConsumer, CheckedSupplier and CheckedFunction are checked analogs of lib functions which can be used independently of Try

CheckedBuilder is the interface for handling exceptions in some checked function. orTry allows execute another same type function if previous was failed. handle provides exception handling including exception type filtering. The order of handlers is important. Reduce methods unsafe and rethrow rethrows last exception in the execution chain. Reduce methods orElse and orElseGet return alternate value like Optional ones if all functions failed. Also there is method suppress. CheckedWrapper is the common implementation of CheckedBuilder.

final class Try {

    public static <T> CheckedBuilder<Supplier<T>, CheckedSupplier<T>, T> 
        safe(CheckedSupplier<T> supplier) {
        return new CheckedWrapper<>(supplier, 
                (current, next, handler, orResult) -> () -> {
            try { return current.get(); } catch (Exception ex) {
                handler.accept(ex);
                return next.isPresent() ? next.get().get() : orResult.apply(ex);
            }
        });
    }

    public static <T> Supplier<T> unsafe(CheckedSupplier<T> supplier) {
        return supplier;
    }

    public static <T> CheckedBuilder<Consumer<T>, CheckedConsumer<T>, Void> 
        safe(CheckedConsumer<T> consumer) {
        return new CheckedWrapper<>(consumer, 
                (current, next, handler, orResult) -> t -> {
            try { current.accept(t); } catch (Exception ex) {
                handler.accept(ex);
                if (next.isPresent()) {
                    next.get().accept(t);
                } else {
                    orResult.apply(ex);
                }
            }
        });
    }

    public static <T> Consumer<T> unsafe(CheckedConsumer<T> consumer) {
        return consumer;
    }

    public static <T, R> CheckedBuilder<Function<T, R>, CheckedFunction<T, R>, R> 
        safe(CheckedFunction<T, R> function) {
        return new CheckedWrapper<>(function, 
                (current, next, handler, orResult) -> t -> {
            try { return current.applyUnsafe(t); } catch (Exception ex) {
                handler.accept(ex);
                return next.isPresent() ? next.get().apply(t) : orResult.apply(ex);
            }
        });
    }

    public static <T, R> Function<T, R> unsafe(CheckedFunction<T, R> function) {
        return function;
    }

    @SuppressWarnings ("unchecked")
    static <T, E extends Throwable> T throwAsUnchecked(Throwable exception) throws E { 
        throw (E) exception; 
    }
}

@FunctionalInterface interface CheckedConsumer<T> extends Consumer<T> {
    void acceptUnsafe(T t) throws Exception;
    @Override default void accept(T t) {
        try { acceptUnsafe(t); } catch (Exception ex) {
            Try.throwAsUnchecked(ex);
        }
    }
}

@FunctionalInterface interface CheckedFunction<T, R> extends Function<T, R> {
    R applyUnsafe(T t) throws Exception;
    @Override default R apply(T t) {
        try { return applyUnsafe(t); } catch (Exception ex) {
            return Try.throwAsUnchecked(ex);
        }
    }
}

@FunctionalInterface interface CheckedSupplier<T> extends Supplier<T> {
    T getUnsafe() throws Exception;
    @Override default T get() {
        try { return getUnsafe(); } catch (Exception ex) {
            return Try.throwAsUnchecked(ex);
        }
    }
}

interface ReduceFunction<TSafe, TUnsafe, R> {
    TSafe wrap(TUnsafe current, Optional<TSafe> next, 
            Consumer<Throwable> handler, Function<Throwable, R> orResult);
}

interface CheckedBuilder<TSafe, TUnsafe, R> {
    CheckedBuilder<TSafe, TUnsafe, R> orTry(TUnsafe next);

    CheckedBuilder<TSafe, TUnsafe, R> handle(Consumer<Throwable> handler);

    <E extends Throwable> CheckedBuilder<TSafe, TUnsafe, R> handle(
            Class<E> exceptionType, Consumer<E> handler);

    CheckedBuilder<TSafe, TUnsafe, R> handleLast(Consumer<Throwable> handler);

    <E extends Throwable> CheckedBuilder<TSafe, TUnsafe, R> handleLast(
            Class<E> exceptionType, Consumer<? super E> handler);

    TSafe unsafe();
    TSafe rethrow(Function<Throwable, Exception> transformer);
    TSafe suppress();
    TSafe orElse(R value);
    TSafe orElseGet(Supplier<R> valueProvider);
}

final class CheckedWrapper<TSafe, TUnsafe, R> 
        implements CheckedBuilder<TSafe, TUnsafe, R> {

    private final TUnsafe function;
    private final ReduceFunction<TSafe, TUnsafe, R> reduceFunction;

    private final CheckedWrapper<TSafe, TUnsafe, R> root;
    private CheckedWrapper<TSafe, TUnsafe, R> next;

    private Consumer<Throwable> handlers = ex -> { };
    private Consumer<Throwable> lastHandlers = ex -> { };

    CheckedWrapper(TUnsafe function, 
            ReduceFunction<TSafe, TUnsafe, R> reduceFunction) {
        this.function = function;
        this.reduceFunction = reduceFunction;
        this.root = this;
    }

    private CheckedWrapper(TUnsafe function, 
            CheckedWrapper<TSafe, TUnsafe, R> prev) {
        this.function = function;
        this.reduceFunction = prev.reduceFunction;
        this.root = prev.root;
        prev.next = this;
    }

    @Override public CheckedBuilder<TSafe, TUnsafe, R> orTry(TUnsafe next) {
        return new CheckedWrapper<>(next, this);
    }

    @Override public CheckedBuilder<TSafe, TUnsafe, R> handle(
            Consumer<Throwable> handler) {
        handlers = handlers.andThen(handler);
        return this;
    }

    @Override public <E extends Throwable> CheckedBuilder<TSafe, TUnsafe, R> 
        handle(Class<E> exceptionType, Consumer<E> handler) {
        handlers = handlers.andThen(ex -> {
            if (exceptionType.isInstance(ex)) {
                handler.accept(exceptionType.cast(ex));
            }
        });
        return this;
    }

    @Override public CheckedBuilder<TSafe, TUnsafe, R> handleLast(
            Consumer<Throwable> handler) {
        lastHandlers = lastHandlers.andThen(handler);
        return this;
    }

    @Override public <E extends Throwable> CheckedBuilder<TSafe, TUnsafe, R> 
        handleLast(Class<E> exceptionType, Consumer<? super E> handler) {
        lastHandlers = lastHandlers.andThen(ex -> {
            if (exceptionType.isInstance(ex)) {
                handler.accept(exceptionType.cast(ex));
            }
        });
        return this;
    }

    @Override public TSafe unsafe() {
        return root.reduce(ex -> Try.throwAsUnchecked(ex));
    }

    @Override
    public TSafe rethrow(Function<Throwable, Exception> transformer) {
        return root.reduce(ex -> Try.throwAsUnchecked(transformer.apply(ex)));
    }

    @Override public TSafe suppress() {
        return root.reduce(ex -> null);
    }

    @Override public TSafe orElse(R value) {
        return root.reduce(ex -> value);
    }

    @Override public TSafe orElseGet(Supplier<R> valueProvider) {
        Objects.requireNonNull(valueProvider);
        return root.reduce(ex -> valueProvider.get());
    }

    private TSafe reduce(Function<Throwable, R> orResult) {
        return reduceFunction.wrap(function, 
                Optional.ofNullable(next).map(p -> p.reduce(orResult)), 
                this::handle, orResult);
    }

    private void handle(Throwable ex) {
        for (CheckedWrapper<TSafe, TUnsafe, R> current = this; 
                current != null; 
                current = current.next) {
            current.handlers.accept(ex);
        }
        lastHandlers.accept(ex);
    }
}

Get img thumbnails from Vimeo?

In javascript (uses jQuery):

function vimeoLoadingThumb(id){    
    var url = "http://vimeo.com/api/v2/video/" + id + ".json?callback=showThumb";

    var id_img = "#vimeo-" + id;

    var script = document.createElement( 'script' );
    script.src = url;

    $(id_img).before(script);
}


function showThumb(data){
    var id_img = "#vimeo-" + data[0].id;
    $(id_img).attr('src',data[0].thumbnail_medium);
}

To display it :

<img id="vimeo-{{ video.id_video }}" src="" alt="{{ video.title }}" />
<script type="text/javascript">
  vimeoLoadingThumb({{ video.id_video }});
</script>

Is there such a thing as min-font-size and max-font-size?

You can use Sass to control min and max font sizes. Here is a brilliant solution by Eduardo Boucas.

https://eduardoboucas.com/blog/2015/06/18/viewport-sized-typography-with-minimum-and-maximum-sizes.html

@mixin responsive-font($responsive, $min, $max: false, $fallback: false) {
  $responsive-unitless: $responsive / ($responsive - $responsive + 1);
  $dimension: if(unit($responsive) == 'vh', 'height', 'width');
  $min-breakpoint: $min / $responsive-unitless * 100;

  @media (max-#{$dimension}: #{$min-breakpoint}) {
    font-size: $min;
  }

  @if $max {
    $max-breakpoint: $max / $responsive-unitless * 100;

    @media (min-#{$dimension}: #{$max-breakpoint}) {
      font-size: $max;
    }
  }

  @if $fallback {
    font-size: $fallback;
  }

  font-size: $responsive;
}

.limit-min {
  @include responsive-font(3vw, 20px);
}

.limit-min-max {
  @include responsive-font(3vw, 20px, 50px);
}

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

You could just create a new database and then go to tasks, import data, and import all the data from the database you want to duplicate to the database you just created.

Convert a python UTC datetime to a local datetime using only python standard library?

I think I figured it out: computes number of seconds since epoch, then converts to a local timzeone using time.localtime, and then converts the time struct back into a datetime...

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

It applies the summer/winter DST correctly:

>>> utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)
>>> utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

I had the same problem. I managed to solve it by simply updating my version of jquery. I was using 1.6.1 and updated to 1.7.1 - no more crashes.

How to create a drop-down list?

You need a Spinner. Here it is an example:

spinner_1 = (Spinner) findViewById(R.id.spinner1);
spinner_1.setOnItemSelectedListener(this);
List<String> list = new ArrayList<String>(); 
list.add("RANJITH");
list.add("ARUN");
list.add("JEESMON");
list.add("NISAM");
list.add("SREEJITH");
list.add("SANJAY");
list.add("AKSHY");
list.add("FIROZ");
list.add("RAHUL");
list.add("ARJUN");
list.add("SAVIYO");
list.add("VISHNU");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_1.setAdapter(adapter);


spinner_2 = (Spinner) findViewById(R.id.spinner_two);
spinner_2.setOnItemSelectedListener(this);
List<String> city = new ArrayList<String>();
city.add("KASARGOD");
city.add("KANNUR");
city.add("THRISSUR");
city.add("KOZHIKODE");
city.add("TRIVANDRUM");
city.add("ERNAMKULLAM");
city.add("WAYANAD");
city.add("PALAKKAD");
city.add("ALAPUZHA");
city.add("IDUKKI");
city.add("KOTTAYAM");
city.add("PATHANAMTHITTA");
city.add("KOLLAM");
city.add("MALAPPURAM");
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, city);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_2.setAdapter(adapter2);

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "YOUR SELECTION IS : " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();


}

@Override
public void onNothingSelected(AdapterView<?> parent) {
    // TODO Auto-generated method stub

}

How to find the largest file in a directory and its subdirectories?

This lists files recursively if they're normal files, sorts by the 7th field (which is size in my find output; check yours), and shows just the first file.

find . -type f -ls | sort +7 | head -1

The first option to find is the start path for the recursive search. A -type of f searches for normal files. Note that if you try to parse this as a filename, you may fail if the filename contains spaces, newlines or other special characters. The options to sort also vary by operating system. I'm using FreeBSD.

A "better" but more complex and heavier solution would be to have find traverse the directories, but perhaps use stat to get the details about the file, then perhaps use awk to find the largest size. Note that the output of stat also depends on your operating system.

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

I encountered the same problem with:

Spring Boot version = 1.5.10
Spring Security version = 4.2.4


The problem occurred on the endpoints, where the ModelAndView viewName was defined with a preceding forward slash. Example:

ModelAndView mav = new ModelAndView("/your-view-here");

If I removed the slash it worked fine. Example:

ModelAndView mav = new ModelAndView("your-view-here");

I also did some tests with RedirectView and it seemed to work with a preceding forward slash.

Oracle SQL - DATE greater than statement

You need to convert the string to date using the to_date() function

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');

This will work only if OrderDate is stored in Date format. If it is Varchar you should apply to_date() func on that column also like

 SELECT * FROM OrderArchive
    WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

If you have MFA enabled on GitLab you should go to Repository Settings/Repository ->Deploy Keys and create one, then use it as login while importing repo on GitHub

Why is the parent div height zero when it has floated children

Ordinarily, floats aren't counted in the layout of their parents.

To prevent that, add overflow: hidden to the parent.

JavaScript: How to find out if the user browser is Chrome?

Works for me on Chrome on Mac. Seems to be or simpler or more reliable (in case userAgent string tested) than all above.

        var isChrome = false;
        if (window.chrome && !window.opr){
            isChrome = true;
        }
        console.log(isChrome);

LINQ to Entities how to update a record

In most cases @tster's answer will suffice. However, I had a scenario where I wanted to update a row without first retrieving it.

My situation is this: I've got a table where I want to "lock" a row so that only a single user at a time will be able to edit it in my app. I'm achieving this by saying

update items set status = 'in use', lastuser = @lastuser, lastupdate = @updatetime where ID = @rowtolock and @status = 'free'

The reason being, if I were to simply retrieve the row by ID, change the properties and then save, I could end up with two people accessing the same row simultaneously. This way, I simply send and update claiming this row as mine, then I try to retrieve the row which has the same properties I just updated with. If that row exists, great. If, for some reason it doesn't (someone else's "lock" command got there first), I simply return FALSE from my method.

I do this by using context.Database.ExecuteSqlCommand which accepts a string command and an array of parameters.

Just wanted to add this answer to point out that there will be scenarios in which retrieving a row, updating it, and saving it back to the DB won't suffice and that there are ways of running a straight update statement when necessary.

Maven: Non-resolvable parent POM

Just for reference.

The joys of Maven.

Putting the relative path of the modules to ../pom.xml solved it.

The parent element has a relativePath element that you need to point to the directory of the parent. It defaults to ..

What does the arrow operator, '->', do in Java?

This one is useful as well when you want to implement a functional interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.print("Run method");
        }
};

Swift - How to detect orientation changes

You can use viewWillTransition(to:with:) and tap into animate(alongsideTransition:completion:) to get the interface orientation AFTER the transition is complete. You just have to define and implement a protocol similar to this in order to tap into the event. Note that this code was used for a SpriteKit game and your specific implementation may differ.

protocol CanReceiveTransitionEvents {
    func viewWillTransition(to size: CGSize)
    func interfaceOrientationChanged(to orientation: UIInterfaceOrientation)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        guard
            let skView = self.view as? SKView,
            let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }

        coordinator.animate(alongsideTransition: nil) { _ in
            if let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation {
                canReceiveRotationEvents.interfaceOrientationChanged(to: interfaceOrientation)
            }
        }

        canReceiveRotationEvents.viewWillTransition(to: size)
    }

You can set breakpoints in these functions and observe that interfaceOrientationChanged(to orientation: UIInterfaceOrientation) is always called after viewWillTransition(to size: CGSize) with the updated orientation.

Excel "External table is not in the expected format."

I recently had this "System.Data.OleDb.OleDbException (0x80004005): External table is not in the expected format." error occur. I was relying on Microsoft Access 2010 Runtime. Prior to the update that was automatically installed on my server on December 12th 2018 my C# code ran fine using Microsoft.ACE.OLEDB.12.0 provider. After the update from December 12th 2018 was installed I started to get the “External table is not in the expected format" in my log file.

I ditched the Microsoft Access 2010 Runtime and installed the Microsoft Access 2013 Runtime and my C# code started to work again with no "System.Data.OleDb.OleDbException (0x80004005): External table is not in the expected format." errors.

2013 version that fixed this error for me https://www.microsoft.com/en-us/download/confirmation.aspx?id=39358

2010 version that worked for me prior to the update that was automatically installed on my server on December 12th. https://www.microsoft.com/en-us/download/confirmation.aspx?id=10910 https://www.microsoft.com/en-us/download/confirmation.aspx?id=10910

I also had this error occur last month in an automated process. The C# code ran fine when I ran it debugging. I found that the service account running the code also needed permissions to the C:\Windows\Temp folder.

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

Rename Oracle Table or View

In order to rename a table in a different schema, try:

ALTER TABLE owner.mytable RENAME TO othertable;

The rename command (as in "rename mytable to othertable") only supports renaming a table in the same schema.

Get random sample from list while maintaining ordering of items?

Following code will generate a random sample of size 4:

import random

sample_size = 4
sorted_sample = [
    mylist[i] for i in sorted(random.sample(range(len(mylist)), sample_size))
]

(note: with Python 2, better use xrange instead of range)

Explanation

random.sample(range(len(mylist)), sample_size)

generates a random sample of the indices of the original list.

These indices then get sorted to preserve the ordering of elements in the original list.

Finally, the list comprehension pulls out the actual elements from the original list, given the sampled indices.

Refresh an asp.net page on button click

When you say refresh the page, its new instance of the page that you are creating so you need to either have a static variable/session variable or a method to store and retrieve the count of hits on your page.

As far as refreshing the page is concerned, Response.Redirect(Request.RawUrl); or window.location=window.location would do the job for you.

What is the difference between RTP or RTSP in a streaming server?

You are getting something wrong... RTSP is a realtime streaming protocol. Meaning, you can stream whatever you want in real time. So you can use it to stream LIVE content (no matter what it is, video, audio, text, presentation...). RTP is a transport protocol which is used to transport media data which is negotiated over RTSP.

You use RTSP to control media transmission over RTP. You use it to setup, play, pause, teardown the stream...

So, if you want your server to just start streaming when the URL is requested, you can implement some sort of RTP-only server. But if you want more control and if you are streaming live video, you must use RTSP, because it transmits SDP and other important decoding data.

Read the documents I linked here, they are a good starting point.

How to set viewport meta for iPhone that handles rotation properly?

just want to share, i've played around with the viewport settings for my responsive design, if i set the Max scale to 0.8, the initial scale to 1 and scalable to no then i get the smallest view in portrait mode and the iPad view for landscape :D... this is properly an ugly hack but it seems to work, i don't know why so i won't be using it, but interesting results

<meta name="viewport" content="user-scalable=no, initial-scale = 1.0,maximum-scale = 0.8,width=device-width" />

enjoy :)

Transfer files to/from session I'm logged in with PuTTY

Transferring files with Putty (pscp/plink.exe)

The default putty installation provides multiple ways to transfer files. Most likely putty is on your default path, so you can directly call putty from the command prompt. If it doesnt, you may have to change your environmental variables. See instructions here: https://it.cornell.edu/managed-servers/transfer-files-using-putt

Steps

  1. Open command prompt by typing cmd

  2. To transfer folders from your Windows computer to another Windows computer use (notice the -r flag, which indicates that the files will be transferred recursively, no need to zip them up): pscp -r -i C:/Users/username/.ssh/id_rsa.ppk "C:/Program Files (x86)/Terminal PC" [email protected]:/"C:/Program Files (x86)/"

  3. To transfer files from your Windows computer to another Windows computer use: pscp -i C:/Users/username/.ssh/id_rsa.ppk "C:/Program Files (x86)/Terminal PC" [email protected]:/"C:/Program Files (x86)/"

  4. Sometimes, you may only have plink installed. plink can potentially be used to transfer files, but its best restricted to simple text files. It may have unknown behavior with binary files (https://superuser.com/questions/1289455/create-text-file-on-remote-machine-using-plink-putty-with-contents-of-windows-lo): plink -i C:/Users/username/.ssh/id_rsa.ppk user@host <localfile "cat >hostfile"

  5. To transfer files from a linux server to a Windows computer to a Linux computer use pscp -r -i C:/Users/username/.ssh/id_rsa.ppk "C:/Program Files (x86)/Terminal PC" [email protected]:/home/username

For all these to work, you need to have the proper public/private key. To generate that for putty see: https://superuser.com/a/1285789/658319

Difference between Node object and Element object?

Node is used to represent tags in general. Divided to 3 types:

Attribute Note: is node which inside its has attributes. Exp: <p id=”123”></p>

Text Node: is node which between the opening and closing its have contian text content. Exp: <p>Hello</p>

Element Node : is node which inside its has other tags. Exp: <p><b></b></p>

Each node may be types simultaneously, not necessarily only of a single type.

Element is simply a element node.

gnuplot plotting multiple line graphs

Whatever your separator is in your ls.dat, you can specify it to gnuplot:

set datafile separator "\t"

How to add property to object in PHP >= 5.3 strict mode without generating error

Yes, is possible to dynamically add properties to a PHP object.

This is useful when a partial object is received from javascript.

JAVASCRIPT side:

var myObject = { name = "myName" };
$.ajax({ type: "POST", url: "index.php",
    data: myObject, dataType: "json",
    contentType: "application/json;charset=utf-8"
}).success(function(datareceived){
    if(datareceived.id >= 0 ) { /* the id property has dynamically added on server side via PHP */ }
});

PHP side:

$requestString = file_get_contents('php://input');
$myObject = json_decode($requestString); // same object as was sent in the ajax call
$myObject->id = 30; // This will dynamicaly add the id property to the myObject object

OR JUST SEND A DUMMY PROPERTY from javascript that you will fill in PHP.

Node/Express file upload

const http          = require('http');
const fs            = require('fs');

// https://www.npmjs.com/package/formidable
const formidable    = require('formidable');

// https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js
const path          = require('path');

router.post('/upload', (req, res) => {
    console.log(req.files);

    let oldpath = req.files.fileUploaded.path;

    // https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js       
    let newpath = path.resolve( `./${req.files.fileUploaded.name}` );

    // copy
    // https://stackoverflow.com/questions/43206198/what-does-the-exdev-cross-device-link-not-permitted-error-mean
    fs.copyFile( oldpath, newpath, (err) => {

        if (err) throw err;

        // delete
        fs.unlink( oldpath, (err) => {

            if (err) throw err;

            console.log('Success uploaded")
        } );                

    } );

});

Android - How to download a file from a webserver

You should use an AsyncTask (or other way to perform a network operation on background).

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //create and execute the download task
    MyAsyncTask async = new MyAsyncTask();
    async.execute();

}

private class MyAsyncTask extends AsyncTask<Void, Void, Void>{

    //execute on background (out of the UI thread)
    protected Long doInBackground(URL... urls) {
        DownloadFiles();
    }

}

More info about AsyncTask on Android documentation

Hope it helps.

Where to get this Java.exe file for a SQL Developer installation

If you have Java installed, java.exe will be in the bin directory. If you can't find it, download and install Java, then use the install path + "\bin".

Validate that a string is a positive integer

return ((parseInt(str, 10).toString() == str) && str.indexOf('-') === -1);

won't work if you give a string like '0001' though

PreparedStatement with Statement.RETURN_GENERATED_KEYS

You can either use the prepareStatement method taking an additional int parameter

PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)

For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:

PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})

SQL Server: Get table primary key using sql query

Keep in mind that if you want to get exact primary field you need to put TABLE_NAME and TABLE_SCHEMA into the condition.

this solution should work:

select COLUMN_NAME from information_schema.KEY_COLUMN_USAGE 
where CONSTRAINT_NAME='PRIMARY' AND TABLE_NAME='TABLENAME' 
AND TABLE_SCHEMA='DATABASENAME'

Editing the git commit message in GitHub

No, because the commit message is related with the commit SHA / hash, and if we change it the commit SHA is also changed. The way I used is to create a comment on that commit. I can't think the other way.

How do I remove the file suffix and path portion from a path string in Bash?

Using basename I used the following to achieve this:

for file in *; do
    ext=${file##*.}
    fname=`basename $file $ext`

    # Do things with $fname
done;

This requires no a priori knowledge of the file extension and works even when you have a filename that has dots in it's filename (in front of it's extension); it does require the program basename though, but this is part of the GNU coreutils so it should ship with any distro.

Counter inside xsl:for-each loop

position(). E.G.:

<countNo><xsl:value-of select="position()" /></countNo>

Real-world examples of recursion

Recursion is a very basic programming technique, and it lends itself to so many problems that listing them is like listing all problems that can be solved by using addition of some kind. Just going through my Lisp solutions for Project Euler, I find: a cross total function, a digit matching function, several functions for searching a space, a minimal text parser, a function splitting a number into the list of its decimal digits, a function constructing a graph, and a function traversing an input file.

The problem is that many if not most mainstream programming languages today do not have tail call optimization so that deep recursion is not feasible with them. This inadequacy means that most programmers are forced to unlearn this natural way of thinking and instead rely on other, arguably less elegant looping constructs.

Stripping everything but alphanumeric chars from a string in Python

You could try:

print ''.join(ch for ch in some_string if ch.isalnum())

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

How to get a user's client IP address in ASP.NET?

In NuGet package install Microsoft.AspNetCore.HttpOverrides Then try:

public class ClientDeviceInfo
    {
        private readonly IHttpContextAccessor httpAccessor;

        public ClientDeviceInfo(IHttpContextAccessor httpAccessor)
        {
            this.httpAccessor = httpAccessor;
        }

        public string GetClientLocalIpAddress()
        {
            return httpAccessor.HttpContext.Connection.LocalIpAddress.ToString();
        }

        public string GetClientRemoteIpAddress()
        {
            return httpAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
        }

        public string GetClientLocalPort()
        {
            return httpAccessor.HttpContext.Connection.LocalPort.ToString();
        }

        public string GetClientRemotePort()
        {
            return httpAccessor.HttpContext.Connection.RemotePort.ToString();
        }
     }

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

Something like:

find /path/ -type f -exec stat \{} --printf="%y\n" \; | 
     sort -n -r | 
     head -n 1

Explanation:

  • the find command will print modification time for every file recursively ignoring directories (according to the comment by IQAndreas you can't rely on the folders timestamps)
  • sort -n (numerically) -r (reverse)
  • head -n 1: get the first entry

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

Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?

jQuery append() vs appendChild()

appendChild is a DOM vanilla-js function.

append is a jQuery function.

They each have their own quirks.

List the queries running on SQL Server

You can run the sp_who command to get a list of all the current users, sessions and processes. You can then run the KILL command on any spid that is blocking others.

How to write MySQL query where A contains ( "a" or "b" )

I user for searching the size of motorcycle :

For example : Data = "Tire cycle size 70 / 90 - 16"

i can search with "70 90 16"

$searchTerms = preg_split("/[\s,-\/?!]+/", $itemName);

foreach ($searchTerms as $term) {
        $term = trim($term);
            if (!empty($term)) {
            $searchTermBits[] = "name LIKE '%$term%'";
            }
        }

$query = "SELECT * FROM item WHERE " .implode(' AND ', $searchTermBits);

How to mark-up phone numbers?

this worked for me:

1.make a standards compliant link:

        <a href="tel:1500100900">

2.replace it when mobile browser is not detected, for skype:

$("a.phone")
    .each(function()
{ 
  this.href = this.href.replace(/^tel/, 
     "callto");
});

Selecting link to replace via class seems more efficient. Of course it works only on anchors with .phone class.

I have put it in function if( !isMobile() ) { ... so it triggers only when detects desktop browser. But this one is problably obsolete...

function isMobile() {
    return (
        ( navigator.userAgent.indexOf( "iPhone" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "iPod" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "iPad" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "Android" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "webOS" ) > -1 )
    );
}

What is the difference between GitHub and gist?

GitHub Gists

To gist or not to gist. That is the $64 question ...

GitHub Gists are Single ( or, multiple ) Simple Markdown Files with repo-like qualities that can be forked or cloned ( if public ).

Otherwise, not if private.

Kinda like a fancy scratch pad that can be shared.

Similar to this comment scratch pad that I am typing on now, but a bit more elaborate.

Whereas, an official, full GitHub repo is a full blown repository of source code src, supporting documents ( markdown or html, or both ) docs or root, images png, ico, svg, and a config.sys file for running Yaml variables hosted on a Jekyll server.

Does a simple Gist file support Yaml front matter?

Me thinks not.

From the official GitHub Gist documentation ...

The gist editor is powered by CodeMirror.

However, you can copy a public Gist ( or, a private Gist if the owner has granted you access via a link to the private Gist ) ...

And, you can then embed that public Gist into an "official" repo page.md using Visual Studio Code, as follows:

"You can embed a gist in any text field that supports Javascript, such as a blog post."

"To get the embed code, click the clipboard icon next to the Embed URL button of a gist."

Now, that's a cool feature.

Makes me want to search ( discover ) other peoples' gists, or OPG and incorporate their "public" work into my full-blown working repos.

"You can discover the PUBLIC gists others have created by going to the gist home page and clicking on the link ...

All Gists{:title='Click to Review the Discover Feature at GitHub Gists'}{:target='_blank'}."

Caveat. No support for Liquid tags at GitHub Gist.

I suppose if I do find something beneficial, I can always ping-back, or cite that source if I do use the work in my full-blown working repos.

Where is the implicit license posted for all gists made public by their authors?

Robert

P.S. This is a good comment. I think I will turn this into a gist and make it publically searchable over at GitHub Gists.

Note. When embedding the <script></script> html tag within the body of a Markdown (.md) file, you may get a warning "MD033" from your linter.

This should not, however, affect the rendering of the data ( src ) called from within the script tag.

To change the default warning flag to accommodate the called contents of a script tag from within Visual Studio Code, add an entry to the Markdownlint Configuration Object within the User Settings Json file, as follows:

// Begin Markdownlint Configuration Object
"markdownlint.config": {
  "MD013": false,
  "MD033": {"allowed_elements": ["script"]}
}// End Markdownlint Configuration Object

Note. Solution derived from GitHub Commit by David Anson

Download files from server php

To read directory contents you can use readdir() and use a script, in my example download.php, to download files

if ($handle = opendir('/path/to/your/dir/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }
    closedir($handle);
}

In download.php you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php

$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;

if(!file_exists($file)){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
}

Language Books/Tutorials for popular languages

For Java EE 5 there's a separate tutorial JEE tutorial. That's useful, as people often ask about persistence and xml binding in java.

Create a CSV File for a user in PHP

Instead of:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

Use:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    echo implode(",", $row)."\n";
}

Preventing form resubmission

The only way to be 100% sure the same form never gets submitted twice is to embed a unique identifier in each one you issue and track which ones have been submitted at the server. The pitfall there is that if the user backs up to the page where the form was and enters new data, the same form won't work.

Java: unparseable date exception

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().

private String modifyDateLayout(String inputDate) throws ParseException{
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
    return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.

Update: Okay, I did a test:

public static void main(String[] args) throws Exception {
    String inputDate = "2010-01-04 01:32:27 UTC";
    String newDate = new Test().modifyDateLayout(inputDate);
    System.out.println(newDate);
}

This correctly prints:

03.01.2010 21:32:27

(I'm on GMT-4)

Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

How to use andWhere and orWhere in Doctrine?

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder:

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.

How to align footer (div) to the bottom of the page?

I am a newbie and these methods are not working for me. However, I tried a margin-top property in css and simply added the value of content pixels +5.

Example: my content layout had a height of 1000px so I put a margin-top value of 1005px in the footer css which gave me a 5px border and a footer that sits delightfully at the bottom of my site.

Probably an amateur way of doing it, but EFFECTIVE!!!

How do you create a static class in C++?

This is similar to C#'s way of doing it in C++

In C# file.cs you can have private var inside a public function. When in another file you can use it by calling the namespace with the function as in:

MyNamespace.Function(blah);

Here's how to imp the same in C++:

SharedModule.h

class TheDataToBeHidden
{
  public:
    static int _var1;
    static int _var2;
};

namespace SharedData
{
  void SetError(const char *Message, const char *Title);
  void DisplayError(void);
}

SharedModule.cpp

//Init the data (Link error if not done)
int TheDataToBeHidden::_var1 = 0;
int TheDataToBeHidden::_var2 = 0;


//Implement the namespace
namespace SharedData
{
  void SetError(const char *Message, const char *Title)
  {
    //blah using TheDataToBeHidden::_var1, etc
  }

  void DisplayError(void)
  {
    //blah
  }
}

OtherFile.h

#include "SharedModule.h"

OtherFile.cpp

//Call the functions using the hidden variables
SharedData::SetError("Hello", "World");
SharedData::DisplayError();

How to open child forms positioned within MDI parent in VB.NET?

   Private Sub FileMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) handles FileMenu.Click

    Form1.MdiParent = Me
    Form1.Dock = DockStyle.Fill
    Form1.Show()
End Sub

java get file size efficiently

All the test cases in this post are flawed as they access the same file for each method tested. So disk caching kicks in which tests 2 and 3 benefit from. To prove my point I took test case provided by GHAD and changed the order of enumeration and below are the results.

Looking at result I think File.length() is the winner really.

Order of test is the order of output. You can even see the time taken on my machine varied between executions but File.Length() when not first, and incurring first disk access won.

---
LENGTH sum: 1163351, per Iteration: 4653.404
CHANNEL sum: 1094598, per Iteration: 4378.392
URL sum: 739691, per Iteration: 2958.764

---
CHANNEL sum: 845804, per Iteration: 3383.216
URL sum: 531334, per Iteration: 2125.336
LENGTH sum: 318413, per Iteration: 1273.652

--- 
URL sum: 137368, per Iteration: 549.472
LENGTH sum: 18677, per Iteration: 74.708
CHANNEL sum: 142125, per Iteration: 568.5

How to fix Cannot find module 'typescript' in Angular 4?

For me just running the below command is not enough (though a valid first step):

npm install -g typescript

The following command is what you need (I think deleting node_modules works too, but the below command is quicker)

npm link typescript

Loaded nib but the 'view' outlet was not set

I ran into something very similar tonight, with a Swift UIViewController subclass. In this case, none of the above fixes worked, but reordering my code a bit did. Net-net, having an extension to the subclass occur before the subclass's definition itself in the same file seems to confuse XCode, despite compiling fine; the fix was to place the extensions after the subclass's definition.

I've posted the details in an answer to this similar question.

ALTER TABLE DROP COLUMN failed because one or more objects access this column

When you alter column datatype you need to change constraint key for every database

  alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];

Install apps silently, with granted INSTALL_PACKAGES permission

you can use this in terminal or shell

adb shell install -g MyApp.apk

see more in develope google

How to set shape's opacity?

use this code below as progress.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient
                    android:startColor="#ff9d9e9d"
                    android:centerColor="#ff5a5d5a"
                    android:centerY="0.75"
                    android:endColor="#ff747674"
                    android:angle="270"
            />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

</layer-list>

where:

  • "progress" is current progress before the thumb and "secondaryProgress" is the progress after thumb.
  • color="#00000000" is a perfect transparency
  • NOTE: the file above is from default android res and is for 2.3.7, it is available on android sources at: frameworks/base/core/res/res/drawable/progress_horizontal.xml. For newer versions you must find the default drawable file for the seekbar corresponding to your android version.

after that use it in the layout containing the xml:

<SeekBar
    android:id="@+id/myseekbar"
    ...
    android:progressDrawable="@drawable/progress"
    />

you can also customize the thumb by using a custom icon seek_thumb.png:

android:thumb="@drawable/seek_thumb"

Use string value from a cell to access worksheet of same name

You need INDIRECT function:

=INDIRECT("'"&A5&"'!G7")

"could not find stored procedure"

Could not find stored procedure?---- means when you get this.. our code like this

String sp="{call GetUnitReferenceMap}";

stmt=conn.prepareCall(sp);

ResultSet rs = stmt.executeQuery();

while (rs.next()) {

currencyMap.put(rs.getString(1).trim(), rs.getString(2).trim()); 

I have 4 DBs(sample1, sample2, sample3) But stmt will search location is master Default DB then we will get Exception.

we should provide DB name then problem resolves::

String sp="{call sample1..GetUnitReferenceMap}";

sql server convert date to string MM/DD/YYYY

select convert(varchar(10), cast(fmdate as date), 101) from sery

Without cast I was not getting fmdate converted, so fmdate was a string.

Gradle DSL method not found: 'runProguard'

runProguard has been renamed to minifyEnabled in version 0.14.0 (2014/10/31) or more in Gradle.

To fix this, you need to change runProguard to minifyEnabled in the build.gradle file of your project.

enter image description here

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

Shorten string without cutting words in JavaScript

Here is a solution in one line.

_x000D_
_x000D_
text = "this is a long string I cant display"_x000D_
_x000D_
function shorten(text,max) {_x000D_
    return text && text.length > max ? text.slice(0,max).split(' ').slice(0, -1).join(' ') : text_x000D_
}_x000D_
_x000D_
_x000D_
console.log(shorten(text,10));
_x000D_
_x000D_
_x000D_

How do I print a double value without scientific notation using Java?

I think everyone had the right idea, but all answers were not straightforward. I can see this being a very useful piece of code. Here is a snippet of what will work:

System.out.println(String.format("%.8f", EnterYourDoubleVariableHere));

the ".8" is where you set the number of decimal places you would like to show.

I am using Eclipse and it worked no problem.

Hope this was helpful. I would appreciate any feedback!

Mockito match any class argument

How about:

when(a.method(isA(A.class))).thenReturn(b);

or:

when(a.method((A)notNull())).thenReturn(b);

How to change the MySQL root account password on CentOS7?

For CentOS 7 and MariaDB 10.4, I had success with the following commands:

su -
systemctl set-environment MYSQLD_OPTS="--skip-grant-tables --user=mysql"
systemctl restart mariadb
mysql -u root

flush privileges;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
flush privileges;
quit

systemctl unset-environment MYSQLD_OPTS
systemctl restart mariadb

jquery UI dialog: how to initialize without a title bar?

I figured out a fix for dynamically removing the title bar.

$("#example").dialog(dialogOpts);
// remove the title bar
$(".ui-dialog-titlebar").hide();

This will remove all elements with the class 'ui-dialog-titlebar' after the dialog box is rendered.

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

Your query is generating a result set so large that it needs to build a temporary table either to hold some of the results or some intermediate product used in generating the result.

The temporary table is being generated in /var/tmp. This temporary table would appear to have been corrupted. Perhaps the device the temporary table was being built on ran out of space. However, usually this would normally result in an "out of space" error. Perhaps something else running on your machine has clobbered the temporary table.

Try reworking your query to use less space, or try reconfiguring your database so that a larger or safer partition is used for temporary tables.

MySQL Manual - B.5.4.4. Where MySQL Stores Temporary Files

How do I programmatically "restart" an Android app?

Here is an example to restart your app in a generic way by using the PackageManager:

Intent i = getBaseContext().getPackageManager()
             .getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

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+).

Group list by values

from operator import itemgetter
from itertools import groupby

lki = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
lki.sort(key=itemgetter(1))

glo = [[x for x,y in g]
       for k,g in  groupby(lki,key=itemgetter(1))]

print glo

.

EDIT

Another solution that needs no import , is more readable, keeps the orders, and is 22 % shorter than the preceding one:

oldlist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]

newlist, dicpos = [],{}
for val,k in oldlist:
    if k in dicpos:
        newlist[dicpos[k]].extend(val)
    else:
        newlist.append([val])
        dicpos[k] = len(dicpos)

print newlist

What is the use of static synchronized method in java?

Java VM contains a single class object per class. Each class may have some shared variables called static variables. If the critical section of the code plays with these variables in a concurrent environment, then we need to make that particular section as synchronized. When there is more than one static synchronized method only one of them will be executed at a time without preemption. That's what lock on class object does.

How to search for rows containing a substring?

Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.

http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Even if WHERE textcolumn LIKE "%SUBSTRING%" is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).

If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")

JavaScript - Replace all commas in a string

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

How To Check If A Key in **kwargs Exists?

DSM's and Tadeck's answers answer your question directly.

In my scripts I often use the convenient dict.pop() to deal with optional, and additional arguments. Here's an example of a simple print() wrapper:

def my_print(*args, **kwargs):
    prefix = kwargs.pop('prefix', '')
    print(prefix, *args, **kwargs)

Then:

>>> my_print('eggs')
 eggs
>>> my_print('eggs', prefix='spam')
spam eggs

As you can see, if prefix is not contained in kwargs, then the default '' (empty string) is being stored in the local prefix variable. If it is given, then its value is being used.

This is generally a compact and readable recipe for writing wrappers for any kind of function: Always just pass-through arguments you don't understand, and don't even know if they exist. If you always pass through *args and **kwargs you make your code slower, and requires a bit more typing, but if interfaces of the called function (in this case print) changes, you don't need to change your code. This approach reduces development time while supporting all interface changes.

Simple and fast method to compare images for similarity

If you want to compare image for similarity,I suggest you to used OpenCV. In OpenCV, there are few feature matching and template matching. For feature matching, there are SURF, SIFT, FAST and so on detector. You can use this to detect, describe and then match the image. After that, you can use the specific index to find number of match between the two images.

Calling a class function inside of __init__

I think that your problem is actually with not correctly indenting init function.It should be like this

class MyClass():
     def __init__(self, filename):
          pass

     def parse_file():
          pass

What is the right way to treat argparse.Namespace() as a dictionary?

Straight from the horse's mouth:

If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

— The Python Standard Library, 16.4.4.6. The Namespace object

Call another rest api from my server in Spring-Boot

Create Bean for Rest Template to auto wiring the Rest Template object.

@SpringBootApplication
public class ChatAppApplication {

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ChatAppApplication.class, args);
    }

}

Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller.

@RequestMapping(value = "/postdata",method = RequestMethod.POST)
    public String PostData(){

       return "{\n" +
               "   \"value\":\"4\",\n" +
               "   \"name\":\"David\"\n" +
               "}";
    }

    @RequestMapping(value = "/post")
    public String getPostResponse(){
        HttpHeaders headers=new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity=new HttpEntity<String>(headers);
        return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
    }

Refer this tutorial[1]

[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm

Input type "number" won't resize

Incorrect usage.

Input type number it's made to have selectable value via arrows up and down.

So basically you are looking for "width" CSS style.

Input text historically is formatted with monospaced font, so size it's also the width it takes.

Input number it's new and "size" property has no sense at all*. A typical usage:

<input type="number" name="quantity" min="1" max="5">

w3c docs

to fix, add a style:

<input type="number" name="email" style="width: 7em">

EDIT: if you want a range, you have to set type="range" and not ="number"

EDIT2: *size is not an allowed value (so, no sense). Check out official W3C specifications

Note: The size attribute works with the following input types: text, search, tel, url, email, and password.

Tip: To specify the maximum number of characters allowed in the element, use the maxlength attribute.

Resolving a Git conflict with binary files

You can also overcome this problem with

git mergetool

which causes git to create local copies of the conflicted binary and spawn your default editor on them:

  • {conflicted}.HEAD
  • {conflicted}
  • {conflicted}.REMOTE

Obviously you can't usefully edit binaries files in a text editor. Instead you copy the new {conflicted}.REMOTE file over {conflicted} without closing the editor. Then when you do close the editor git will see that the undecorated working-copy has been changed and your merge conflict is resolved in the usual way.

Must issue a STARTTLS command first

Adding

props.put("mail.smtp.starttls.enable", "true");

solved my problem ;)

My problem was :

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. u186sm7971862pfu.82 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.example.sendmail.SendEmailExample2.main(SendEmailExample2.java:53)

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

You can also implement like this to return Success and Error on a same request mapping method,use Object class(Parent class of every class in java) :-

public ResponseEntity< Object> method() {                                                                                                                                                                                                                                                                                                                                                                                  
    boolean b = //  logic  here   
      if (b)  
        return new ResponseEntity< Object>(HttpStatus.OK);      
    else      
        return new ResponseEntity< Object>(HttpStatus.CONFLICT); //appropriate error code   
}

How to embed images in html email

Based on Arthur Halma's answer, I did the following that works correctly with Apple's, Android & iOS mail.

define("EMAIL_DOMAIN", "yourdomain.com");

public function send_email_html($to, $from, $subject, $html) {
  preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
  $i = 0;
  $paths = array();
  foreach ($matches[1] as $img) {
    $img_old = $img;
    if(strpos($img, "http://") == false) {
      $uri = parse_url($img);
      $paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
      $content_id = md5($img);
      $html = str_replace($img_old,'cid:'.$content_id,$html);
      $paths[$i++]['cid'] = $content_id;
    }
  }
  $uniqid   = md5(uniqid(time()));
  $boundary = "--==_mimepart_".$uniqid;

  $headers = "From: ".$from."\n".
  'Reply-to: '.$from."\n".
  'Return-Path: '.$from."\n".
  'Message-ID: <'.$uniqid.'@'.EMAIL_DOMAIN.">\n".
  'Date: '.gmdate('D, d M Y H:i:s', time())."\n".
  'Mime-Version: 1.0'."\n".
  'Content-Type: multipart/related;'."\n".
  '  boundary='.$boundary.";\n".
  '  charset=UTF-8'."\n".
  'X-Mailer: PHP/' . phpversion();

  $multipart = '';
  $multipart .= "--$boundary\n";
  $kod = 'UTF-8';
  $multipart .= "Content-Type: text/html; charset=$kod\n";
  $multipart .= "Content-Transfer-Encoding: 7-bit\n\n";
  $multipart .= "$html\n\n";
  foreach ($paths as $path) {
    if (file_exists($path['path']))
      $fp = fopen($path['path'],"r");
      if (!$fp)  {
        return false;
      }
    $imagetype = substr(strrchr($path['path'], '.' ),1);
    $file = fread($fp, filesize($path['path']));
    fclose($fp);
    $message_part = "";
    switch ($imagetype) {
      case 'png':
      case 'PNG':
            $message_part .= "Content-Type: image/png";
            break;
      case 'jpg':
      case 'jpeg':
      case 'JPG':
      case 'JPEG':
            $message_part .= "Content-Type: image/jpeg";
            break;
      case 'gif':
      case 'GIF':
            $message_part .= "Content-Type: image/gif";
            break;
    }
    $message_part .= "; file_name = \"$path\"\n";
    $message_part .= 'Content-ID: <'.$path['cid'].">\n";
    $message_part .= "Content-Transfer-Encoding: base64\n";
    $message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
    $message_part .= chunk_split(base64_encode($file))."\n";
    $multipart .= "--$boundary\n".$message_part."\n";
  }
  $multipart .= "--$boundary--\n";
  mail($to, $subject, $multipart, $headers);
}

Best way to check for IE less than 9 in JavaScript without library

You could do it in a quick and dirty fashion with a regular expression and .match():

if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
    // ie less than version 9
}

How can I get list of values from dict?

You can use * operator to unpack dict_values:

>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']

or list object

>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']

How do I select between the 1st day of the current month and current day in MySQL?

I used this one

select DATE_ADD(DATE_SUB(LAST_DAY(now()), INTERVAL  1 MONTH),INTERVAL  1 day) first_day
      ,LAST_DAY(now()) last_day, date(now()) today_day

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

Image resizing client-side with JavaScript before upload to the server

The answer to this is yes - in HTML 5 you can resize images client-side using the canvas element. You can also take the new data and send it to a server. See this tutorial:

http://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/

sh: react-scripts: command not found after running npm start

if anyone is willing to use npm only, then run this npm i react-native-scripts --save, then npm start or whatever the command you use

What exactly is LLVM?

LLVM is a library that is used to construct, optimize and produce intermediate and/or binary machine code.

LLVM can be used as a compiler framework, where you provide the "front end" (parser and lexer) and the "back end" (code that converts LLVM's representation to actual machine code).

LLVM can also act as a JIT compiler - it has support for x86/x86_64 and PPC/PPC64 assembly generation with fast code optimizations aimed for compilation speed.

Unfortunately disabled since 2013, there was the ability to play with LLVM's machine code generated from C or C++ code at the demo page.

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

Determining the version of Java SDK on the Mac

The simplest solution would be open terminal

$ java -version

it shows the following

java version "1.6.0_65"
  1. Stefan's solution also works for me. Here's the exact input:

$ cd /System/Library/Frameworks/JavaVM.framework/Versions

$ ls -l

Below is the last line of output:

lrwxr-xr-x   1 root  wheel   59 Feb 12 14:57 CurrentJDK -> /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents

1.6.0.jdk would be the answer

Angularjs error Unknown provider

Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:

angular.module('myApp', ['myApp.directives', 'myApp.services']);

plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview

Set Google Maps Container DIV width and height 100%

Setting Map Container to position to relative do the trick. Here is HTML.

<body>
    <!-- Map container -->
    <div id="map_canvas"></div>
</body>

And Simple CSS.

<style>
html, body, #map_canvas {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
#map_canvas {
    position: relative;
}
</style>

Tested on all browsers. Here is the Screenshot.

enter image description here

How to use filter, map, and reduce in Python 3

You can read about the changes in What's New In Python 3.0. You should read it thoroughly when you move from 2.x to 3.x since a lot has been changed.

The whole answer here are quotes from the documentation.

Views And Iterators Instead Of Lists

Some well-known APIs no longer return lists:

  • [...]
  • map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).
  • [...]

Builtins

  • [...]
  • Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.
  • [...]

How to break out from a ruby block?

next and break seem to do the correct thing in this simplified example!

class Bar
  def self.do_things
      Foo.some_method(1..10) do |x|
            next if x == 2
            break if x == 9
            print "#{x} "
      end
  end
end

class Foo
    def self.some_method(targets, &block)
      targets.each do |target|
        begin
          r = yield(target)
        rescue  => x
          puts "rescue #{x}"
        end
     end
   end
end

Bar.do_things

output: 1 3 4 5 6 7 8

apache not accepting incoming connections from outside of localhost

SELinux prevents Apache (and therefore all Apache modules) from making remote connections by default.

# setsebool -P httpd_can_network_connect=1

Call int() function on every list element?

Thought I'd consolidate the answers and show some timeit results.

Python 2 sucks pretty bad at this, but map is a bit faster than comprehension.

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
116.25092001434314
>>> timeit.timeit('map(int, l)', setup)
106.66044823117454

Python 3 is over 4x faster by itself, but converting the map generator object to a list is still faster than comprehension, and creating the list by unpacking the map generator (thanks Artem!) is slightly faster still.

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
25.133059591551955
>>> timeit.timeit('list(map(int, l))', setup)
19.705547827217515
>>> timeit.timeit('[*map(int, l)]', setup)
19.45838406513076

Note: In Python 3, 4 elements seems to be the crossover point (3 in Python 2) where comprehension is slightly faster, though unpacking the generator is still faster than either for lists with more than 1 element.

How to know if .keyup() is a character key (jQuery)

This helped for me:

$("#input").keyup(function(event) {
        //use keyup instead keypress because:
        //- keypress will not work on backspace and delete
        //- keypress is called before the character is added to the textfield (at least in google chrome) 
        var searchText = $.trim($("#input").val());

        var c= String.fromCharCode(event.keyCode);
        var isWordCharacter = c.match(/\w/);
        var isBackspaceOrDelete = (event.keyCode == 8 || event.keyCode == 46);

        // trigger only on word characters, backspace or delete and an entry size of at least 3 characters
        if((isWordCharacter || isBackspaceOrDelete) && searchText.length > 2)
        { ...

BeanFactory not initialized or already closed - call 'refresh' before

I had this issue until I removed the project in question from the server's deployments (in JBoss Dev Studio, right-click the server and "Remove" the project in the Servers view), then did the following:

  1. Restarted the JBoss EAP 6.1 server without any projects deployed.
  2. Once the server had started, I then added the project in question to the server.

After this, just restart the server (in debug or run mode) by selecting the server, NOT the project itself.

This seemed to flush any previous settings/states/memory/whatever that was causing the issue, and I no longer got the error.

React component not re-rendering on state change

I'd like to add to this the enormously simple, but oh so easily made mistake of writing:

this.state.something = 'changed';

... and then not understanding why it's not rendering and Googling and coming on this page, only to realize that you should have written:

this.setState({something: 'changed'});

React only triggers a re-render if you use setState to update the state.

ssl.SSLError: tlsv1 alert protocol version

I got this problem too. In macos, here is the solution:

  • Step 1: brew restall python. now you got python3.7 instead of the old python

  • Step 2: build the new env base on python3.7. my path is /usr/local/Cellar/python/3.7.2/bin/python3.7

now, you'll not being disturbed by this problem.

Server.UrlEncode vs. HttpUtility.UrlEncode

Server.UrlEncode() is there to provide backward compatibility with Classic ASP,

Server.UrlEncode(str);

Is equivalent to:

HttpUtility.UrlEncode(str, Response.ContentEncoding);

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

The accepted answer is ok, but I had difficulties to understand it. So here is a simple example to clarify it.

In my ajax request I had a standard Authorization header.

$$(document).on('ajaxStart', function(e){
var auth_token = localStorage.getItem(SB_TOKEN_MOBILE);
if( auth_token ) {
    var xhr = e.detail.xhr;

    xhr.setRequestHeader('**Authorization**', 'Bearer ' + auth_token);
}

This code produces the error in the question. What I had to do in my nodejs server was to add Authorization in allowed headers:

res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,**Authorization**');

Is it possible to preview stash contents in git?

I use this to see all my stashes with colour diff highlighting (on Fedora 21):

git stash list | 
  awk -F: '{ print "\n\n\n\n"; print $0; print "\n\n"; 
  system("git -c color.ui=always stash show -p " $1); }' | 
  less -R

(Adapted from Git: see what's in a stash without applying stash)

Limit the size of a file upload (html input element)

_x000D_
_x000D_
const input = document.getElementById('input')_x000D_
_x000D_
input.addEventListener('change', (event) => {_x000D_
  const target = event.target_x000D_
   if (target.files && target.files[0]) {_x000D_
_x000D_
      /*Maximum allowed size in bytes_x000D_
        5MB Example_x000D_
        Change first operand(multiplier) for your needs*/_x000D_
      const maxAllowedSize = 5 * 1024 * 1024;_x000D_
      if (target.files[0].size > maxAllowedSize) {_x000D_
       // Here you can ask your users to load correct file_x000D_
        target.value = ''_x000D_
      }_x000D_
  }_x000D_
})
_x000D_
<input type="file" id="input" />
_x000D_
_x000D_
_x000D_

How to read until end of file (EOF) using BufferedReader in Java?

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.

MySQL 'Order By' - sorting alphanumeric correctly

This should sort alphanumeric field like: 1/ Number only, order by 1,2,3,4,5,6,7,8,9,10,11 etc... 2/ Then field with text like: 1foo, 2bar, aaa11aa, aaa22aa, b5452 etc...

SELECT  MyField
FROM MyTable
order by 
    IF( MyField REGEXP '^-?[0-9]+$' = 0, 
    9999999999 ,  
    CAST(MyField AS DECIMAL) 
    ), MyField

The query check if the data is a number, if not put it to 9999999999 , then order first on this column, then order on data with text

Good luck!

Select distinct values from a table field

By example:

# select distinct code from Platform where id in ( select platform__id from Build where product=p)
pl_ids = Build.objects.values('platform__id').filter(product=p)
platforms = Platform.objects.values_list('code', flat=True).filter(id__in=pl_ids).distinct('code')
platforms = list(platforms) if platforms else []

Unexpected end of file error

If you do not use precompiled headers in your project, set the Create/Use Precompiled Header property of source files to Not Using Precompiled Headers. To set this compiler option, follow these steps:

  • In the Solution Explorer pane of the project, right-click the project name, and then click Properties.
  • In the left pane, click the C/C++ folder.
  • Click the Precompiled Headers node.
  • In the right pane, click Create/Use Precompiled Header, and then click Not Using Precompiled Headers.

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

I had the similar issue. The problem was in the passwords: the Keystore and private key used different passwords. (KeyStore explorer was used)

After creating Keystore with the same password as private key had the issue was resolved.

Illegal character in path at index 16

Did you try this?

new File("<PATH OF YOUR FILE>").toURI().toString();

document.getElementById vs jQuery $()

A note on the difference in speed. Attach the following snipet to an onclick call:

function myfunc()
{
    var timer = new Date();
    
        for(var i = 0; i < 10000; i++)
        {
            //document.getElementById('myID');
            $('#myID')[0];
        }
    

    console.log('timer: ' + (new Date() - timer));
}

Alternate commenting one out and then comment the other out. In my tests,

document.getElementbyId averaged about 35ms (fluctuating from 25ms up to 52ms on about 15 runs)

On the other hand, the

jQuery averaged about 200ms (ranging from 181ms to 222ms on about 15 runs).

From this simple test you can see that the jQuery took about 6 times as long.

Of course, that is over 10000 iterations so in a simpler situation I would probably use the jQuery for ease of use and all of the other cool things like .animate and .fadeTo. But yes, technically getElementById is quite a bit faster.

After installation of Gulp: “no command 'gulp' found”

I actually have the same issue.

This link is probably my best guess:

nodejs vs node on ubuntu 12.04

I did that to resolve my problem:

sudo apt-get --purge remove node 
sudo apt-get --purge remove nodejs 
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node

batch script - read line by line

Try this:

@echo off
for /f "tokens=*" %%a in (input.txt) do (
  echo line=%%a
)
pause

because of the tokens=* everything is captured into %a

edit: to reply to your comment, you would have to do that this way:

@echo off
for /f "tokens=*" %%a in (input.txt) do call :processline %%a

pause
goto :eof

:processline
echo line=%*

goto :eof

:eof

Because of the spaces, you can't use %1, because that would only contain the part until the first space. And because the line contains quotes, you can also not use :processline "%%a" in combination with %~1. So you need to use %* which gets %1 %2 %3 ..., so the whole line.

Shorthand if/else statement Javascript

Here is a way to do it that works, but may not be best practise for any language really:

var x,y;
x='something';
y=1;
undefined === y || (x = y);

alternatively

undefined !== y && (x = y);

C# 4.0 optional out/ref arguments

What about like this?

public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
    return true;
}

You still have to pass a value to the parameter from C# but it is an optional ref param.

Adding a collaborator to my free GitHub account?

In the repository, click Admin, then go to the Collaborators tab.

Return 0 if field is null in MySQL

None of the above answers were complete for me. If your field is named field, so the selector should be the following one:

IFNULL(`field`,0) AS field

For example in a SELECT query:

SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`

Hope this can help someone to not waste time.

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

How to revert uncommitted changes including files and folders?

Use:

git reset HEAD filepath

For example:

git reset HEAD om211/src/META-INF/persistence.xml

Ignore case in Python strings

I'm pretty sure you either have to use .lower() or use a regular expression. I'm not aware of a built-in case-insensitive string comparison function.

Request exceeded the limit of 10 internal redirects due to probable configuration error

I just found a solution to the problem here:

http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/

The .htaccess file in webroot should look like:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

instead of this:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /projectname
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

To bring more confusion in this already rich thread, I happened to bump in the same unresolved external on fprintf

main.obj : error LNK2019: unresolved external symbol __imp__fprintf referenced in function _GenerateInfoFile

Even if in my case it was in a rather different context : under Visual Studio 2005 (Visual Studio 8.0) and the error was happening in my own code (the very same I was compiling), not a third party.

It happened that this error was triggered by /MD option in my compiler flags. Switching to /MT removed the issue. This is weird because usually, linking statically (MT) raises more problem than dynamically (MD)... but just in case it serves other, I put it there.

How to convert java.lang.Object to ArrayList?

You can create a util method that converts any collection to a java list

public static List<?> convertObjectToList(Object obj) {
    List<?> list = new ArrayList<>();
    if (obj.getClass().isArray()) {
        list = Arrays.asList((Object[])obj);
    } else if (obj instanceof Collection) {
        list = new ArrayList<>((Collection<?>)obj);
    }
    return list;
}

you can also mix with this validation below:

public static boolean isCollection(Object obj) {
  return obj.getClass().isArray() || obj instanceof Collection;
}

Best way to style a TextBox in CSS

You can use:

input[type=text]
{
 /*Styles*/
}

Define your common style attributes inside this. and for extra style you can add a class then.

URL to load resources from the classpath in Java

From Java 9+ and up, you can define a new URLStreamHandlerProvider. The URL class uses the service loader framework to load it at run time.

Create a provider:

package org.example;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.spi.URLStreamHandlerProvider;

public class ClasspathURLStreamHandlerProvider extends URLStreamHandlerProvider {

    @Override
    public URLStreamHandler createURLStreamHandler(String protocol) {
        if ("classpath".equals(protocol)) {
            return new URLStreamHandler() {
                @Override
                protected URLConnection openConnection(URL u) throws IOException {
                    return ClassLoader.getSystemClassLoader().getResource(u.getPath()).openConnection();
                }
            };
        }
        return null;
    }

}

Create a file called java.net.spi.URLStreamHandlerProvider in the META-INF/services directory with the contents:

org.example.ClasspathURLStreamHandlerProvider

Now the URL class will use the provider when it sees something like:

URL url = new URL("classpath:myfile.txt");

Selecting one row from MySQL using mysql_* API

Ultimately, I want to be able to echo out a signle field like so:

   $row['option_value']

So why don't you? It should work.

Import an existing git project into GitLab?

Moving a project from GitHub to GitLab including issues, pull requests Wiki, Milestones, Labels, Release notes and comments

There is a thorough instruction on GitLab Docs:

https://docs.gitlab.com/ee/user/project/import/github.html

tl;dr

  • Ensure that any GitHub users who you want to map to GitLab users have either:

    • A GitLab account that has logged in using the GitHub icon - or -
    • A GitLab account with an email address that matches the public email address of the GitHub user
  • From the top navigation bar, click + and select New project.

  • Select the Import project tab and then select GitHub.
  • Select the first button to List your GitHub repositories. You are redirected to a page on github.com to authorize the GitLab application.
  • Click Authorize gitlabhq. You are redirected back to GitLab's Import page and all of your GitHub repositories are listed.
  • Continue on to selecting which repositories to import.

But Please read the GitLab Docs page for details and hooks!

(it's not much)

Stop form from submitting , Using Jquery

use this too :

if(e.preventDefault) 
   e.preventDefault(); 
else 
   e.returnValue = false;

Becoz e.preventDefault() is not supported in IE( some versions ). In IE it is e.returnValue = false

How to display my application's errors in JSF?

You also have to include the FormID in your call to addMessage().

 FacesContext.getCurrentInstance().addMessage("myform:newPassword1", new FacesMessage("Error: Your password is NOT strong enough."));

This should do the trick.

Regards.

In Python, how do I iterate over a dictionary in sorted key order?

If you want to sort by the order that items were inserted instead of of the order of the keys, you should have a look to Python's collections.OrderedDict. (Python 3 only)

Submitting a multidimensional array via POST with php

I made a function which handles arrays as well as single GET or POST values

function subVal($varName, $default=NULL,$isArray=FALSE ){ // $isArray toggles between (multi)array or single mode

    $retVal = "";
    $retArray = array();

    if($isArray) {
        if(isset($_POST[$varName])) {
            foreach ( $_POST[$varName] as $var ) {  // multidimensional POST array elements
                $retArray[]=$var;
            }
        }
        $retVal=$retArray;
    }

    elseif (isset($_POST[$varName]) )  {  // simple POST array element
        $retVal = $_POST[$varName];
    }

    else {
        if (isset($_GET[$varName]) ) {
            $retVal = $_GET[$varName];    // simple GET array element
        }
        else {
            $retVal = $default;
        }
    }

    return $retVal;

}

Examples:

$curr_topdiameter = subVal("topdiameter","",TRUE)[3];
$user_name = subVal("user_name","");

Passing structs to functions

bool data(sampleData *data)
{
}

You need to tell the method which type of struct you are using. In this case, sampleData.

Note: In this case, you will need to define the struct prior to the method for it to be recognized.

Example:

struct sampleData
{
   int N;
   int M;
   // ...
};

bool data(struct *sampleData)
{

}

int main(int argc, char *argv[]) {

      sampleData sd;
      data(&sd);

}

Note 2: I'm a C guy. There may be a more c++ish way to do this.

how to stop a running script in Matlab

If ctrl+c doesn't respond right away because your script is too long/complex, hold it.

The break command doesn't run when matlab is executing some of its deeper scripts, and either it won't log a ctrl sequence in the buffer, or it clears the buffer just before or just after it completes those pieces of code. In either case, when matlab returns to execute more of your script, it will recognize that you are holding ctrl+c and terminate.

For longer running programs, I usually try to find a good place to provide a status update and I always accompany that with some measure of time using tic and toc. Depending on what I am doing, I might use run time, segment time, some kind of average, etc...

For really long running programs, I found this to be exceptionally useful http://www.mathworks.com/matlabcentral/fileexchange/16649-send-text-message-to-cell-phone/content/send_text_message.m

but it looks like they have some newer functions for this too.

Laravel 5 – Clear Cache in Shared Hosting Server

This package is for php ^7.0 and ^laravel5.5.

Use this package in cronjob that I have created for this purpose only. I was also facing same situation. https://packagist.org/packages/afrazahmad/clear-cached-data Install it and run:

php artisan clear:data

and it will run the following commands automcatically

php artisan cache:clear
php artisan view:clear
php artisan route:clear
php artisan clear-compiled
php artisan config:cache

Hope it helps.

If you want to run it automatically at specific time then you will have to setup crnjob first. e.g.

 in app/console/kernel.php

In schedule function:

$schedule->command('clear:data')->dailyAt('07:00');

select certain columns of a data table

You can create a method that looks like this:

  public static DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2)
    {
        DataTable TempTable = RecordDT_;

        System.Data.DataView view = new System.Data.DataView(TempTable);
        System.Data.DataTable selected = view.ToTable("Selected", false, col1, col2);
        return selected;
    }

You can return as many columns as possible.. just add the columns as call parameters as shown below:

public DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2,string col3,...)

and also add the parameters to this line:

System.Data.DataTable selected = view.ToTable("Selected", false,col1, col2,col3,...);

Then simply implement the function as:

 DataTable myselectedColumnTable=SelectedColumns(OriginalTable,"Col1","Col2",...);

Thanks...

Write string to output stream

Streams (InputStream and OutputStream) transfer binary data. If you want to write a string to a stream, you must first convert it to bytes, or in other words encode it. You can do that manually (as you suggest) using the String.getBytes(Charset) method, but you should avoid the String.getBytes() method, because that uses the default encoding of the JVM, which can't be reliably predicted in a portable way.

The usual way to write character data to a stream, though, is to wrap the stream in a Writer, (often a PrintWriter), that does the conversion for you when you call its write(String) (or print(String)) method. The corresponding wrapper for InputStreams is a Reader.

PrintStream is a special OutputStream implementation in the sense that it also contain methods that automatically encode strings (it uses a writer internally). But it is still a stream. You can safely wrap your stream with a writer no matter if it is a PrintStream or some other stream implementation. There is no danger of double encoding.

Example of PrintWriter with OutputStream:

try (PrintWriter p = new PrintWriter(new FileOutputStream("output-text.txt", true))) {
    p.println("Hello");
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
}

How to debug Apache mod_rewrite

For basic URL resolution, use a command line fetcher like wget or curl to do the testing, rather than a manual browser. Then you don't have to clear any cache; just up arrow and Enter in a shell to re-run your test fetches.

How do you execute an arbitrary native command from a string?

If you want to use the call operator, the arguments can be an array stored in a variable:

$prog = 'c:\windows\system32\cmd.exe'
$myargs = '/c','dir','/x'
& $prog $myargs

The call operator works with ApplicationInfo objects too.

$prog = get-command cmd
$myargs = -split '/c dir /x'
& $prog $myargs

How do I do word Stemming or Lemmatization?

I tried your list of terms on this snowball demo site and the results look okay....

  • cats -> cat
  • running -> run
  • ran -> ran
  • cactus -> cactus
  • cactuses -> cactus
  • community -> communiti
  • communities -> communiti

A stemmer is supposed to turn inflected forms of words down to some common root. It's not really a stemmer's job to make that root a 'proper' dictionary word. For that you need to look at morphological/orthographic analysers.

I think this question is about more or less the same thing, and Kaarel's answer to that question is where I took the second link from.

CSS display:inline property with list-style-image: property on <li> tags

I would suggest not to use list-style-image, as it behaves quite differently in different browsers, especially the image position

instead, you can use something like this

ol.widgets,
ol.widgets li { list-style: none; }
ol.widgets li { padding-left: 20px; backgroud: transparent ("image") no-repeat x y; }

it works in all browsers and would give you the identical result in different browsers.

Element-wise addition of 2 lists?

Use map with lambda function:

>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]

Download single files from GitHub

  1. On the right hand side just below "Clone in Desktop" it say's "Download Zip file"
  2. Download Zip File
  3. Extract the file

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

The accepted answer worked fine for me, but expanding on gimenete's answer, I wanted a generic template I could use to pass through all query/path/header params (just as strings for now), and I came up the following template. I'm posting it here in case someone finds it useful:

#set($keys = [])
#foreach($key in $input.params().querystring.keySet())
  #set($success = $keys.add($key))
#end

#foreach($key in $input.params().headers.keySet())
  #if(!$keys.contains($key))
    #set($success = $keys.add($key))
  #end
#end

#foreach($key in $input.params().path.keySet())
  #if(!$keys.contains($key))
    #set($success = $keys.add($key))
  #end
#end

{
#foreach($key in $keys)
  "$key": "$util.escapeJavaScript($input.params($key))"#if($foreach.hasNext),#end
#end
}

Node.js/Express.js App Only Works on Port 3000

In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www. I just changed the statement in bin/www.

How do you remove the title text from the Android ActionBar?

i use this code in App manifest

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:logo="@drawable/logo2"
        android:label="@string/title_text"
        android:theme="@style/Theme.Zinoostyle" >

my logo file is 200*800 pixel and use this code in main activity.java

getActionBar().setDisplayShowTitleEnabled(false);

it will work Corectly

Find size of an array in Perl

There are various ways to print size of an array. Here are the meanings of all:

Let’s say our array is my @arr = (3,4);

Method 1: scalar

This is the right way to get the size of arrays.

print scalar @arr;  # Prints size, here 2

Method 2: Index number

$#arr gives the last index of an array. So if array is of size 10 then its last index would be 9.

print $#arr;     # Prints 1, as last index is 1
print $#arr + 1; # Adds 1 to the last index to get the array size

We are adding 1 here, considering the array as 0-indexed. But, if it's not zero-based then, this logic will fail.

perl -le 'local $[ = 4; my @arr = (3, 4); print $#arr + 1;'   # prints 6

The above example prints 6, because we have set its initial index to 4. Now the index would be 5 and 6, with elements 3 and 4 respectively.

Method 3:

When an array is used in a scalar context, then it returns the size of the array

my $size = @arr;
print $size;   # Prints size, here 2

Actually, method 3 and method 1 are same.

Read Excel File in Python

The approach I took reads the header information from the first row to determine the indexes of the columns of interest.

You mentioned in the question that you also want the values output to a string. I dynamically build a format string for the output from the FORMAT column list. Rows are appended to the values string separated by a new line char.

The output column order is determined by the order of the column names in the FORMAT list.

In my code below the case of the column name in the FORMAT list is important. In the question above you've got 'Pincode' in your FORMAT list, but 'PinCode' in your excel. This wouldn't work below, it would need to be 'PinCode'.

from xlrd import open_workbook
wb = open_workbook('sample.xls')

FORMAT = ['Arm_id', 'DSPName', 'PinCode']
values = ""

for s in wb.sheets():
    headerRow = s.row(0)
    columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == firstRow[x].value]
    formatString = ("%s,"*len(columnIndex))[0:-1] + "\n"

    for row in range(1,s.nrows):
        currentRow = s.row(row)
        currentRowValues = [currentRow[x].value for x in columnIndex]
        values += formatString % tuple(currentRowValues)

print values

For the sample input you gave above this code outputs:

>>> 1.0,JaVAS,282001.0
2.0,JaVAS,282002.0
3.0,JaVAS,282003.0

And because I'm a python noob, props be to: this answer, this answer, this question, this question and this answer.

Display a jpg image on a JPanel

You could also use

ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);

JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);

if your working with a absolut value as layout.

How can I confirm a database is Oracle & what version it is using SQL?

Run this SQL:

select * from v$version;

And you'll get a result like:

BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE    10.2.0.3.0      Production
TNS for Solaris: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production

Padding a table row

You could simply add this style to the table.

table {
    border-spacing: 15px;
}

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Misconception Common misconception with column ordering is that, I should (or could) do the pushing and pulling on mobile devices, and that the desktop views should render in the natural order of the markup. This is wrong.

Reality Bootstrap is a mobile first framework. This means that the order of the columns in your HTML markup should represent the order in which you want them displayed on mobile devices. This mean that the pushing and pulling is done on the larger desktop views. not on mobile devices view..

Brandon Schmalz - Full Stack Web Developer Have a look at full description here

Using cURL with a username and password?

Or the same thing but different syntax

curl http://username:[email protected]/test/blah?something=123

How can I find the number of elements in an array?

I used following code as suggested above to evaluate number of elements in my 2-dimensional array:

#include <stdio.h>
#include <string.h>

void main(void)
{
    char strs[3][20] =
    {
        {"January"},
        {"February"},
        {""}
    };

    int arraysize = sizeof(strs)/sizeof(strs[0]);

    for (int i = 0; i < arraysize; i++)
    {
        printf("Month %d is: %s\n", i, strs[i]);
    }

}

It works nicely. As far as I know you can't mix up different data types in C arrays and also you should have the same size of all array elements (if I am right), therefore you can take advantage of that with this little trick:

  1. count number of bytes with sizeof() function from whole 2d array (in this case 3*20 = 60 bytes)
  2. count number of bytes with sizeof() function from first array element strs[0] (in this case 20 bytes)
  3. divide whole size with size of one element what will give you number of elements

This snipped should be portable for 2d arrays in C however in other programming languages it could not work because you can use different data types within array with different sizes (like in JAVA).

Each GROUP BY expression must contain at least one column that is not an outer reference

I just found this error., while using GETDATE() [i.e outer reference] in the group by clause in a select query.

When replaced it with date column from the respective table it cleared.

Thought to share as a simple example. cheers ;)