Programs & Examples On #Gltail

How can I split a text into sentences?

I had to read subtitles files and split them into sentences. After pre-processing (like removing time information etc in the .srt files), the variable fullFile contained the full text of the subtitle file. The below crude way neatly split them into sentences. Probably I was lucky that the sentences always ended (correctly) with a space. Try this first and if it has any exceptions, add more checks and balances.

# Very approximate way to split the text into sentences - Break after ? . and !
fullFile = re.sub("(\!|\?|\.) ","\\1<BRK>",fullFile)
sentences = fullFile.split("<BRK>");
sentFile = open("./sentences.out", "w+");
for line in sentences:
    sentFile.write (line);
    sentFile.write ("\n");
sentFile.close;

Oh! well. I now realize that since my content was Spanish, I did not have the issues of dealing with "Mr. Smith" etc. Still, if someone wants a quick and dirty parser...

Node.js Best Practice Exception Handling

Update: Joyent now has their own guide. The following information is more of a summary:

Safely "throwing" errors

Ideally we'd like to avoid uncaught errors as much as possible, as such, instead of literally throwing the error, we can instead safely "throw" the error using one of the following methods depending on our code architecture:

  • For synchronous code, if an error happens, return the error:

    // Define divider as a syncrhonous function
    var divideSync = function(x,y) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by returning it
            return new Error("Can't divide by zero")
        }
        else {
            // no error occured, continue on
            return x/y
        }
    }
    
    // Divide 4/2
    var result = divideSync(4,2)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/2=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/2='+result)
    }
    
    // Divide 4/0
    result = divideSync(4,0)
    // did an error occur?
    if ( result instanceof Error ) {
        // handle the error safely
        console.log('4/0=err', result)
    }
    else {
        // no error occured, continue on
        console.log('4/0='+result)
    }
    
  • For callback-based (ie. asynchronous) code, the first argument of the callback is err, if an error happens err is the error, if an error doesn't happen then err is null. Any other arguments follow the err argument:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    divide(4,2,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/2=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/2='+result)
        }
    })
    
    divide(4,0,function(err,result){
        // did an error occur?
        if ( err ) {
            // handle the error safely
            console.log('4/0=err', err)
        }
        else {
            // no error occured, continue on
            console.log('4/0='+result)
        }
    })
    
  • For eventful code, where the error may happen anywhere, instead of throwing the error, fire the error event instead:

    // Definite our Divider Event Emitter
    var events = require('events')
    var Divider = function(){
        events.EventEmitter.call(this)
    }
    require('util').inherits(Divider, events.EventEmitter)
    
    // Add the divide function
    Divider.prototype.divide = function(x,y){
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by emitting it
            var err = new Error("Can't divide by zero")
            this.emit('error', err)
        }
        else {
            // no error occured, continue on
            this.emit('divided', x, y, x/y)
        }
    
        // Chain
        return this;
    }
    
    // Create our divider and listen for errors
    var divider = new Divider()
    divider.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    divider.on('divided', function(x,y,result){
        console.log(x+'/'+y+'='+result)
    })
    
    // Divide
    divider.divide(4,2).divide(4,0)
    

Safely "catching" errors

Sometimes though, there may still be code that throws an error somewhere which can lead to an uncaught exception and a potential crash of our application if we don't catch it safely. Depending on our code architecture we can use one of the following methods to catch it:

  • When we know where the error is occurring, we can wrap that section in a node.js domain

    var d = require('domain').create()
    d.on('error', function(err){
        // handle the error safely
        console.log(err)
    })
    
    // catch the uncaught errors in this asynchronous or synchronous code block
    d.run(function(){
        // the asynchronous or synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    })
    
  • If we know where the error is occurring is synchronous code, and for whatever reason can't use domains (perhaps old version of node), we can use the try catch statement:

    // catch the uncaught errors in this synchronous code block
    // try catch statements only work on synchronous code
    try {
        // the synchronous code that we want to catch thrown errors on
        var err = new Error('example')
        throw err
    } catch (err) {
        // handle the error safely
        console.log(err)
    }
    

    However, be careful not to use try...catch in asynchronous code, as an asynchronously thrown error will not be caught:

    try {
        setTimeout(function(){
            var err = new Error('example')
            throw err
        }, 1000)
    }
    catch (err) {
        // Example error won't be caught here... crashing our app
        // hence the need for domains
    }
    

    If you do want to work with try..catch in conjunction with asynchronous code, when running Node 7.4 or higher you can use async/await natively to write your asynchronous functions.

    Another thing to be careful about with try...catch is the risk of wrapping your completion callback inside the try statement like so:

    var divide = function(x,y,next) {
        // if error condition?
        if ( y === 0 ) {
            // "throw" the error safely by calling the completion callback
            // with the first argument being the error
            next(new Error("Can't divide by zero"))
        }
        else {
            // no error occured, continue on
            next(null, x/y)
        }
    }
    
    var continueElsewhere = function(err, result){
            throw new Error('elsewhere has failed')
    }
    
    try {
            divide(4, 2, continueElsewhere)
            // ^ the execution of divide, and the execution of 
            //   continueElsewhere will be inside the try statement
    }
    catch (err) {
            console.log(err.stack)
            // ^ will output the "unexpected" result of: elsewhere has failed
    }
    

    This gotcha is very easy to do as your code becomes more complex. As such, it is best to either use domains or to return errors to avoid (1) uncaught exceptions in asynchronous code (2) the try catch catching execution that you don't want it to. In languages that allow for proper threading instead of JavaScript's asynchronous event-machine style, this is less of an issue.

  • Finally, in the case where an uncaught error happens in a place that wasn't wrapped in a domain or a try catch statement, we can make our application not crash by using the uncaughtException listener (however doing so can put the application in an unknown state):

    // catch the uncaught errors that weren't wrapped in a domain or try catch statement
    // do not use this in modules, but only in applications, as otherwise we could have multiple of these bound
    process.on('uncaughtException', function(err) {
        // handle the error safely
        console.log(err)
    })
    
    // the asynchronous or synchronous code that emits the otherwise uncaught error
    var err = new Error('example')
    throw err
    

Can we open pdf file using UIWebView on iOS?

Swift version:

if let docPath = NSBundle.mainBundle().pathForResource("sample", ofType: "pdf") {
    let docURL = NSURL(fileURLWithPath: docPath)
    webView.loadRequest(NSURLRequest(URL: docURL))
}

How to change the output color of echo in Linux

You can use the awesome tput command (suggested in Ignacio's answer) to produce terminal control codes for all kinds of things.


Usage

Specific tput sub-commands are discussed later.

Direct

Call tput as part of a sequence of commands:

tput setaf 1; echo "this is red text"

Use ; instead of && so if tput errors the text still shows.

Shell variables

Another option is to use shell variables:

red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`
echo "${red}red text ${green}green text${reset}"

tput produces character sequences that are interpreted by the terminal as having a special meaning. They will not be shown themselves. Note that they can still be saved into files or processed as input by programs other than the terminal.

Command substitution

It may be more convenient to insert tput's output directly into your echo strings using command substitution:

echo "$(tput setaf 1)Red text $(tput setab 7)and white background$(tput sgr 0)"

Example

The above command produces this on Ubuntu:

Screenshot of colour terminal text


Foreground & background colour commands

tput setab [1-7] # Set the background colour using ANSI escape
tput setaf [1-7] # Set the foreground colour using ANSI escape

Colours are as follows:

Num  Colour    #define         R G B

0    black     COLOR_BLACK     0,0,0
1    red       COLOR_RED       1,0,0
2    green     COLOR_GREEN     0,1,0
3    yellow    COLOR_YELLOW    1,1,0
4    blue      COLOR_BLUE      0,0,1
5    magenta   COLOR_MAGENTA   1,0,1
6    cyan      COLOR_CYAN      0,1,1
7    white     COLOR_WHITE     1,1,1

There are also non-ANSI versions of the colour setting functions (setb instead of setab, and setf instead of setaf) which use different numbers, not given here.

Text mode commands

tput bold    # Select bold mode
tput dim     # Select dim (half-bright) mode
tput smul    # Enable underline mode
tput rmul    # Disable underline mode
tput rev     # Turn on reverse video mode
tput smso    # Enter standout (bold) mode
tput rmso    # Exit standout mode

Cursor movement commands

tput cup Y X # Move cursor to screen postion X,Y (top left is 0,0)
tput cuf N   # Move N characters forward (right)
tput cub N   # Move N characters back (left)
tput cuu N   # Move N lines up
tput ll      # Move to last line, first column (if no cup)
tput sc      # Save the cursor position
tput rc      # Restore the cursor position
tput lines   # Output the number of lines of the terminal
tput cols    # Output the number of columns of the terminal

Clear and insert commands

tput ech N   # Erase N characters
tput clear   # Clear screen and move the cursor to 0,0
tput el 1    # Clear to beginning of line
tput el      # Clear to end of line
tput ed      # Clear to end of screen
tput ich N   # Insert N characters (moves rest of line forward!)
tput il N    # Insert N lines

Other commands

tput sgr0    # Reset text format to the terminal's default
tput bel     # Play a bell

With compiz wobbly windows, the bel command makes the terminal wobble for a second to draw the user's attention.


Scripts

tput accepts scripts containing one command per line, which are executed in order before tput exits.

Avoid temporary files by echoing a multiline string and piping it:

echo -e "setf 7\nsetb 1" | tput -S  # set fg white and bg red

See also

  • See man 1 tput
  • See man 5 terminfo for the complete list of commands and more details on these options. (The corresponding tput command is listed in the Cap-name column of the huge table that starts at line 81.)

How and where to use ::ng-deep?

I would emphasize the importance of limiting the ::ng-deep to only children of a component by requiring the parent to be an encapsulated css class.

For this to work it's important to use the ::ng-deep after the parent, not before otherwise it would apply to all the classes with the same name the moment the component is loaded.

Using the :host keyword before ::ng-deep will handle this automatically:

:host ::ng-deep .mat-checkbox-layout

Alternatively you can achieve the same behavior by adding a component scoped CSS class before the ::ng-deep keyword:

.my-component ::ng-deep .mat-checkbox-layout {
    background-color: aqua;
}

Component template:

<h1 class="my-component">
    <mat-checkbox ....></mat-checkbox>
</h1>

Resulting (Angular generated) css will then include the uniquely generated name and apply only to its own component instance:

.my-component[_ngcontent-c1] .mat-checkbox-layout {
    background-color: aqua;
}

Regular Expressions: Search in list

To do so without compiling the Regex first, use a lambda function - for example:

from re import match

values = ['123', '234', 'foobar']
filtered_values = list(filter(lambda v: match('^\d+$', v), values))

print(filtered_values)

Returns:

['123', '234']

filter() just takes a callable as it's first argument, and returns a list where that callable returned a 'truthy' value.

PHPMailer AddAddress()

foreach ($all_address as $aa) {
    $mail->AddAddress($aa); 
}

What is the best way to seed a database in Rails?

Rails has a built in way to seed data as explained here.

Another way would be to use a gem for more advanced or easy seeding such as: seedbank.

The main advantage of this gem and the reason I use it is that it has advanced capabilities such as data loading dependencies and per environment seed data.

Adding an up to date answer as this answer was first on google.

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

BH's answer of installing Java 6u45 was very close... still got the popup on reboot...BUT after uninstalling Java 6u45, rebooted, no warning! Thank you BH! Then installed the latest version, 8u151-i586, rebooted no warning.

I added lines in PATH as above, didn't do anything.

My system: Windows 7, 64 bit. Warning was for No JVM, 32 bit Java not found. Yes, I could have installed the 64 bit version, but 32bit is more compatible with all programs.

How to open link in new tab on html?

The simple way to open the link in a new tab is to add a target attribute in the link having a value equals to "_blanl", like this :

_x000D_
_x000D_
<a href="http://www.WEBSITE_NAME.com" target="_blank"></a>
_x000D_
_x000D_
_x000D_

Use LIKE %..% with field values in MySQL

Use:

SELECT t1.Notes, 
       t2.Name
  FROM Table1 t1
  JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')

How do I limit the number of decimals printed for a double?

Use the DecimalFormat class to format the double

Simple DateTime sql query

SELECT * 
  FROM TABLENAME 
 WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
   AND [DateTime] <= '2011-05-25 3:35:04 AM'

If this doesn't work, please script out your table and post it here. this will help us get you the correct answer quickly.

Android: upgrading DB version and adding new table

Your code looks correct. My suggestion is that the database already thinks it's upgraded. If you executed the project after incrementing the version number, but before adding the execSQL call, the database on your test device/emulator may already believe it's at version 2.

A quick way to verify this would be to change the version number to 3 -- if it upgrades after that, you know it was just because your device believed it was already upgraded.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This is the real proxy redirection to the intended server.

server {
  listen          80;
  server_name     localhost;
location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
    proxy_pass http://xx.xxx.xxx.xxx/;
    proxy_redirect off;
    proxy_set_header Host $host;

  }
}

Random number in range [min - max] using PHP

I have bundled the answers here and made it version independent;

function generateRandom($min = 1, $max = 20) {
    if (function_exists('random_int')):
        return random_int($min, $max); // more secure
    elseif (function_exists('mt_rand')):
        return mt_rand($min, $max); // faster
    endif;
    return rand($min, $max); // old
}

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

How do you read CSS rule values with JavaScript?

//works in IE, not sure about other browsers...

alert(classes[x].style.cssText);

Replacing accented characters php

I found this way to be a good one, without having to worry too much about charsets and arrays, or iconv:

function replace_accents($str) {
   $str = htmlentities($str, ENT_COMPAT, "UTF-8");
   $str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde|ring);/','$1',$str);
   return html_entity_decode($str);
}

Changing factor levels with dplyr mutate

Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be

df <- iris %>%
  mutate(Species = recode(Species, 
     setosa = "SETOSA",
     versicolor = "VERSICOLOR",
     virginica = "VIRGINICA")
  )

How do I find the length/number of items present for an array?

I'm not sure that i know exactly what you mean.

But to get the length of an initialized array,

doesn't strlen(string) work ??

Why does Java's hashCode() in String use 31 as a multiplier?

A big expectation from hash functions is that their result's uniform randomness survives an operation such as hash(x) % N where N is an arbitrary number (and in many cases, a power of two), one reason being that such operations are used commonly in hash tables for determining slots. Using prime number multipliers when computing the hash decreases the probability that your multiplier and the N share divisors, which would make the result of the operation less uniformly random.

Others have pointed out the nice property that multiplication by 31 can be done by a multiplication and a subtraction. I just want to point out that there is a mathematical term for such primes: Mersenne Prime

All mersenne primes are one less than a power of two so we can write them as:

p = 2^n - 1

Multiplying x by p:

x * p = x * (2^n - 1) = x * 2^n - x = (x << n) - x

Shifts (SAL/SHL) and subtractions (SUB) are generally faster than multiplications (MUL) on many machines. See instruction tables from Agner Fog

That's why GCC seems to optimize multiplications by mersenne primes by replacing them with shifts and subs, see here.

However, in my opinion, such a small prime is a bad choice for a hash function. With a relatively good hash function, you would expect to have randomness at the higher bits of the hash. However, with the Java hash function, there is almost no randomness at the higher bits with shorter strings (and still highly questionable randomness at the lower bits). This makes it more difficult to build efficient hash tables. See this nice trick you couldn't do with the Java hash function.

Some answers mention that they believe it is good that 31 fits into a byte. This is actually useless since:

(1) We execute shifts instead of multiplications, so the size of the multiplier does not matter.

(2) As far as I know, there is no specific x86 instruction to multiply an 8 byte value with a 1 byte value so you would have needed to convert "31" to a 8 byte value anyway even if you were multiplying. See here, you multiply entire 64bit registers.

(And 127 is actually the largest mersenne prime that could fit in a byte.)

Does a smaller value increase randomness in the middle-lower bits? Maybe, but it also seems to greatly increase the possible collisions :).

One could list many different issues but they generally boil down to two core principles not being fulfilled well: Confusion and Diffusion

But is it fast? Probably, since it doesn't do much. However, if performance is really the focus here, one character per loop is quite inefficient. Why not do 4 characters at a time (8 bytes) per loop iteration for longer strings, like this? Well, that would be difficult to do with the current definition of hash where you need to multiply every character individually (please tell me if there is a bit hack to solve this :D).

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

How to find locked rows in Oracle

Given some table, you can find which rows are not locked with SELECT FOR UPDATESKIP LOCKED.

For example, this query will lock (and return) every unlocked row:

SELECT * FROM mytable FOR UPDATE SKIP LOCKED

References

How to know user has clicked "X" or the "Close" button?

I agree with the DialogResult-Solution as the more straight forward one.

In VB.NET however, typecast is required to get the CloseReason-Property

    Private Sub MyForm_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing

        Dim eCast As System.Windows.Forms.FormClosingEventArgs
        eCast = TryCast(e, System.Windows.Forms.FormClosingEventArgs)
        If eCast.CloseReason = Windows.Forms.CloseReason.None Then
            MsgBox("Button Pressed")
        Else
            MsgBox("ALT+F4 or [x] or other reason")
        End If

    End Sub

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

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

Addition to the Usage from the ORM layer in the accepted answer: count(*) can be done for ORM using the query.with_entities(func.count()), like this:

session.query(MyModel).with_entities(func.count()).scalar()

It can also be used in more complex cases, when we have joins and filters - the important thing here is to place with_entities after joins, otherwise SQLAlchemy could raise the Don't know how to join error.

For example:

  • we have User model (id, name) and Song model (id, title, genre)
  • we have user-song data - the UserSong model (user_id, song_id, is_liked) where user_id + song_id is a primary key)

We want to get a number of user's liked rock songs:

SELECT count(*) 
  FROM user_song
  JOIN song ON user_song.song_id = song.id 
 WHERE user_song.user_id = %(user_id)
   AND user_song.is_liked IS 1
   AND song.genre = 'rock'

This query can be generated in a following way:

user_id = 1

query = session.query(UserSong)
query = query.join(Song, Song.id == UserSong.song_id)
query = query.filter(
    and_(
        UserSong.user_id == user_id, 
        UserSong.is_liked.is_(True),
        Song.genre == 'rock'
    )
)
# Note: important to place `with_entities` after the join
query = query.with_entities(func.count())
liked_count = query.scalar()

Complete example is here.

td widths, not working?

You can use within <td> tag css : display:inline-block

Like: <td style="display:inline-block">

Why does the C++ STL not provide any "tree" containers?

In a way, std::map is a tree (it is required to have the same performance characteristics as a balanced binary tree) but it doesn't expose other tree functionality. The likely reasoning behind not including a real tree data structure was probably just a matter of not including everything in the stl. The stl can be looked as a framework to use in implementing your own algorithms and data structures.

In general, if there's a basic library functionality that you want, that's not in the stl, the fix is to look at BOOST.

Otherwise, there's a bunch of libraries out there, depending on the needs of your tree.

Android: alternate layout xml for landscape mode

By default, the layouts in /res/layout are applied to both portrait and landscape.

If you have for example

/res/layout/main.xml

you can add a new folder /res/layout-land, copy main.xml into it and make the needed adjustments.

orientation

See also http://www.androidpeople.com/android-portrait-amp-landscape-differeent-layouts and http://www.devx.com/wireless/Article/40792/1954 for some more options.

fitting data with numpy

Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients in the opposite order of that for np.polyfit and np.polyval (or, as you used np.poly1d). To illustrate:

In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]: 
array([  84.29340848, -100.53595376,   44.83281408,   -8.85931101,
          0.65459882])

In [41]: np.polyfit(x, y, 4)
Out[41]: 
array([   0.65459882,   -8.859311  ,   44.83281407, -100.53595375,
         84.29340846])

In general: np.polynomial.polynomial.polyfit returns coefficients [A, B, C] to A + Bx + Cx^2 + ..., while np.polyfit returns: ... + Ax^2 + Bx + C.

So if you want to use this combination of functions, you must reverse the order of coefficients, as in:

ffit = np.polyval(coefs[::-1], x_new)

However, the documentation states clearly to avoid np.polyfit, np.polyval, and np.poly1d, and instead to use only the new(er) package.

You're safest to use only the polynomial package:

import numpy.polynomial.polynomial as poly

coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)

Or, to create the polynomial function:

ffit = poly.Polynomial(coefs)    # instead of np.poly1d
plt.plot(x_new, ffit(x_new))

fit and data plot

How can I use modulo operator (%) in JavaScript?

That would be the modulo operator, which produces the remainder of the division of two numbers.

Sort array of objects by string property value

If you have duplicate last names you might sort those by first name-

obj.sort(function(a,b){
  if(a.last_nom< b.last_nom) return -1;
  if(a.last_nom >b.last_nom) return 1;
  if(a.first_nom< b.first_nom) return -1;
  if(a.first_nom >b.first_nom) return 1;
  return 0;
});

concatenate two strings

You can use concatenation operator and instead of declaring two variables only use one variable

String finalString =  cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

How to manually set an authenticated user in Spring Security / SpringMVC

The new filtering feature in Servlet 2.4 basically alleviates the restriction that filters can only operate in the request flow before and after the actual request processing by the application server. Instead, Servlet 2.4 filters can now interact with the request dispatcher at every dispatch point. This means that when a Web resource forwards a request to another resource (for instance, a servlet forwarding the request to a JSP page in the same application), a filter can be operating before the request is handled by the targeted resource. It also means that should a Web resource include the output or function from other Web resources (for instance, a JSP page including the output from multiple other JSP pages), Servlet 2.4 filters can work before and after each of the included resources. .

To turn on that feature you need:

web.xml

<filter>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter>  
<filter-mapping>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <url-pattern>/<strike>*</strike></url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

RegistrationController

return "forward:/login?j_username=" + registrationModel.getUserEmail()
        + "&j_password=" + registrationModel.getPassword();

Multiple Indexes vs Multi-Column Indexes

If you have queries that will be frequently using a relatively static set of columns, creating a single covering index that includes them all will improve performance dramatically.

By putting multiple columns in your index, the optimizer will only have to access the table directly if a column is not in the index. I use these a lot in data warehousing. The downside is that doing this can cost a lot of overhead, especially if the data is very volatile.

Creating indexes on single columns is useful for lookup operations frequently found in OLTP systems.

You should ask yourself why you're indexing the columns and how they'll be used. Run some query plans and see when they are being accessed. Index tuning is as much instinct as science.

Trying to SSH into an Amazon Ec2 instance - permission error

Change permission for the key file with :

chmod 400 key-file-name.pem

See AWS documentation for connecting to the instance:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html#EC2_ConnectToInstance_Linux

setTimeout in for-loop does not print consecutive values

You have to arrange for a distinct copy of "i" to be present for each of the timeout functions.

function doSetTimeout(i) {
  setTimeout(function() { alert(i); }, 100);
}

for (var i = 1; i <= 2; ++i)
  doSetTimeout(i);

If you don't do something like this (and there are other variations on this same idea), then each of the timer handler functions will share the same variable "i". When the loop is finished, what's the value of "i"? It's 3! By using an intermediating function, a copy of the value of the variable is made. Since the timeout handler is created in the context of that copy, it has its own private "i" to use.

edit — there have been a couple of comments over time in which some confusion was evident over the fact that setting up a few timeouts causes the handlers to all fire at the same time. It's important to understand that the process of setting up the timer — the calls to setTimeout() — take almost no time at all. That is, telling the system, "Please call this function after 1000 milliseconds" will return almost immediately, as the process of installing the timeout request in the timer queue is very fast.

Thus, if a succession of timeout requests is made, as is the case in the code in the OP and in my answer, and the time delay value is the same for each one, then once that amount of time has elapsed all the timer handlers will be called one after another in rapid succession.

If what you need is for the handlers to be called at intervals, you can either use setInterval(), which is called exactly like setTimeout() but which will fire more than once after repeated delays of the requested amount, or instead you can establish the timeouts and multiply the time value by your iteration counter. That is, to modify my example code:

function doScaledTimeout(i) {
  setTimeout(function() {
    alert(i);
  }, i * 5000);
}

(With a 100 millisecond timeout, the effect won't be very obvious, so I bumped the number up to 5000.) The value of i is multiplied by the base delay value, so calling that 5 times in a loop will result in delays of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds.

Update

Here in 2018, there is a simpler alternative. With the new ability to declare variables in scopes more narrow than functions, the original code would work if so modified:

for (let i = 1; i <= 2; i++) {
    setTimeout(function() { alert(i) }, 100);
}

The let declaration, unlike var, will itself cause there to be a distinct i for each iteration of the loop.

writing to existing workbook using xlwt

Here's some sample code I used recently to do just that.

It opens a workbook, goes down the rows, if a condition is met it writes some data in the row. Finally it saves the modified file.

from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd

START_ROW = 297 # 0 based (subtract 1 from excel row number)
col_age_november = 1
col_summer1 = 2
col_fall1 = 3

rb = open_workbook(file_path,formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy

for row_index in range(START_ROW, r_sheet.nrows):
    age_nov = r_sheet.cell(row_index, col_age_november).value
    if age_nov == 3:
        #If 3, then Combo I 3-4 year old  for both summer1 and fall1
        w_sheet.write(row_index, col_summer1, 'Combo I 3-4 year old')
        w_sheet.write(row_index, col_fall1, 'Combo I 3-4 year old')

wb.save(file_path + '.out' + os.path.splitext(file_path)[-1])

What does Ruby have that Python doesn't, and vice versa?

Ruby gets inheritance right with Single Inheritance

Did I mention Ruby has an EPIC community of developers. Ninja theme inspired by Object Oriented Ruby: Classes, Mixins and Jedi.

Ruby gets inheritance right with Single Inheritance! Needing to use multiple inheritance to express domain relationships is a symptom of an improperly designed system. The confusion multiple inheritance creates isn't worth the added functionality.

Say you have a method called kick:

def kick
  puts "kick executed."
end

What if kick is defined in both class Ninjutsu and class Shaolin? Multiple Inheritance fails here and that's why Python fails:

class Mortal < Ninjutsu, Shaolin
  def initialize
    puts "mortal pwnage."
  end
end

In Ruby if you need a Ninja, you create an instance of the Ninja class. If you need a Shaolin master, you create an instance of the Shaolin class.

ninja = Ninjutsu.new
ninja.kick

or 

master = Shaolin.new
master.kick

Ruby gets inheritance right with Mixins

There might be the off chance that both a Ninja and a Shaolin master share the same kick technique. Read that again - both share the same behavior - nothing else! Python would encourage you to roll a whole new class. Not with Ruby! In Ruby you simply use a Mixin:

module Katas
  def kick
    puts "Temporal Whip Kick."
  end
end

and simply Mixin the Katas module into your Ruby Class:

require 'Katas'

class Moral < Ninjutsu
  include Katas

  def initialize
    puts "mortal pwnage."
  end
end

Then the behavior gets shared - which is what you were really going for. Not an entire class. That's the biggest difference between Ruby and Python - Ruby gets inheritance right!

PHPExcel auto size column width

Here a more flexible variant based on @Mark Baker post:

foreach (range('A', $phpExcelObject->getActiveSheet()->getHighestDataColumn()) as $col) {
        $phpExcelObject->getActiveSheet()
                ->getColumnDimension($col)
                ->setAutoSize(true);
    } 

Hope this helps ;)

REST API error return good practices

As others have pointed, having a response entity in an error code is perfectly allowable.

Do remember that 5xx errors are server-side, aka the client cannot change anything to its request to make the request pass. If the client's quota is exceeded, that's definitly not a server error, so 5xx should be avoided.

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

Cannot find java. Please use the --jdkhome switch

Check the setting in your user config /home/username/.netbeans/version/etc/netbeans.conf

I had the problem where I was specifying the location globally, but my user setting was overriding the global setting.

CentOS 7/Netbeans 8.1

How do I use namespaces with TypeScript external modules?

dog.ts

import b = require('./baseTypes');

export module Living.Things {
    // Error, can't find name 'Animal', ??
    // Solved: can find, if properly referenced; exporting modules is useless, anyhow
    export class Dog extends b.Living.Things.Animal {
        public woof(): void {
            return;
        }
    }
}

tree.ts

// Error, can't use the same name twice, ??
// Solved: cannot declare let or const variable twice in same scope either: just use a different name
import b = require('./baseTypes');
import d = require('./dog');

module Living.Things {
    // Why do I have to write b.Living.Things.Plant instead of b.Plant??
    class Tree extends b.Living.Things.Plant {
    }
}

How to prevent a browser from storing passwords

Here is a pure HTML/CSS solution for Chrome tested in version 65.0.3325.162 (official build) (64-bit).

Set the input type="text" and use CSS text-security:disc to mimic type="password".

<input type="text" name="username">
<input type="text" name="password" style="text-security:disc; -webkit-text-security:disc;">

As far as I have tested this solution works for Chrome, Firefox version 59.0 (64-bit), Internet Explorer version 11.0.9600 as well as the IE Emulators Internet Explorer 5 and greater.

What is the difference between SessionState and ViewState?

Session is used mainly for storing user specific data [ session specific data ]. In the case of session you can use the value for the whole session until the session expires or the user abandons the session. Viewstate is the type of data that has scope only in the page in which it is used. You canot have viewstate values accesible to other pages unless you transfer those values to the desired page. Also in the case of viewstate all the server side control datas are transferred to the server as key value pair in __Viewstate and transferred back and rendered to the appropriate control in client when postback occurs.

How to implement OnFragmentInteractionListener

See your auto-generated Fragment created by Android Studio. When you created the new Fragment, Studio stubbed a bunch of code for you. At the bottom of the auto-generated template there is an inner interface definition called OnFragmentInteractionListener. Your Activity needs to implement this interface. This is the recommended pattern for your Fragment to notify your Activity of events so it can then take appropriate action, such as load another Fragment. See this page for details, look for the "Creating event callbacks for the Activity" section: http://developer.android.com/guide/components/fragments.html

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

Use serialize and deserialize methods in SerializationUtils from commons-lang.

Python locale error: unsupported locale setting

python looks for .UFT-8, but you probably have .utf8 try installing the .UFT-8 packages with sudo dpkg-reconfigure locales

How to change my Git username in terminal?

If you have created a new Github account and you want to push commits with your new account instead of your previous account then the .gitconfig must be updated, otherwise, you will push with the already owned Github account to the new account.

In order to fix this, you have to navigate to your home directory and open the .gitconfig with an editor. The editor can be vim, notepad++, or even notepad.

Once you have the .gitconfig open, just modify the "name" with your new Github account username that you want to push with.

Protect image download

As other answers said, if you can see it you can copy/download it.

To add up to the other answers, just for your information, you can add invisible or tricky watermarks to your images: http://www.cgrats.com/create-an-invisible-watermark-in-photoshop.html (just an example, there are more techniques, just google for invisible watermarks)

Anyway if you want to prove the ownership of your image a good way is to have a bigger resolution copy for yourself, and always publish a lower resolution / size one. Or publish it also on a "public" media like ... deviantart or flickr or something where people can't change the upload date. This way you can prove you had that image before anybody else

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

You can use this tool to create appropriate c# classes:

http://jsonclassgenerator.codeplex.com/

and when you will have classes created you can simply convert string to object:

    public static T ParseJsonObject<T>(string json) where T : class, new()
    {
        JObject jobject = JObject.Parse(json);
        return JsonConvert.DeserializeObject<T>(jobject.ToString());
    }

Here that classes: http://ge.tt/2KGtbPT/v/0?c

Just fix namespaces.

How to add label in chart.js for pie chart

It is not necessary to use another library like newChart or use other people's pull requests to pull this off. All you have to do is define an options object and add the label wherever and however you want it in the tooltip.

var optionsPie = {
    tooltipTemplate: "<%= label %> - <%= value %>"
}

If you want the tooltip to be always shown you can make some other edits to the options:

 var optionsPie = {
        tooltipEvents: [],
        showTooltips: true,
        onAnimationComplete: function() {
            this.showTooltip(this.segments, true);
        },
        tooltipTemplate: "<%= label %> - <%= value %>"
    }

In your data items, you have to add the desired label property and value and that's all.

data = [
    {
        value: 480000,
        color:"#F7464A",
        highlight: "#FF5A5E",
        label: "Tobacco"
    }
];

Now, all you have to do is pass the options object after the data to the new Pie like this: new Chart(ctx).Pie(data,optionsPie) and you are done.

This probably works best for pies which are not very small in size.

Pie chart with labels

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

batch/bat to copy folder and content at once

I've been interested in the original question here and related ones.

For an answer, this week I did some experiments with XCOPY.

To help answer the original question, here I post the results of my experiments.

I did the experiments on Windows 7 64 bit Professional SP1 with the copy of XCOPY that came with the operating system.

For the experiments, I wrote some code in the scripting language Open Object Rexx and the editor macro language Kexx with the text editor KEdit.

XCOPY was called from the Rexx code. The Kexx code edited the screen output of XCOPY to focus on the crucial results.

The experiments all had to do with using XCOPY to copy one directory with several files and subdirectories.

The experiments consisted of 10 cases. Each case adjusted the arguments to XCOPY and called XCOPY once. All 10 cases were attempting to do the same copying operation.

Here are the main results:

(1) Of the 10 cases, only three did copying. The other 7 cases right away, just from processing the arguments to XCOPY, gave error messages, e.g.,

Invalid path

Access denied

with no files copied.

Of the three cases that did copying, they all did the same copying, that is, gave the same results.

(2) If want to copy a directory X and all the files and directories in directory X, in the hierarchical file system tree rooted at directory X, then apparently XCOPY -- and this appears to be much of the original question -- just will NOT do that.

One consequence is that if using XCOPY to copy directory X and its contents, then CAN copy the contents but CANNOT copy the directory X itself; thus, lose the time-date stamp on directory X, its archive bit, data on ownership, attributes, etc.

Of course if directory X is a subdirectory of directory Y, an XCOPY of Y will copy all of the contents of directory Y WITH directory X. So in this way can get a copy of directory X. However, the copy of directory X will have its time-date stamp of the time of the run of XCOPY and NOT the time-date stamp of the original directory X.

This change in time-date stamps can be awkward for a copy of a directory with a lot of downloaded Web pages: The HTML file of the Web page will have its original time-date stamp, but the corresponding subdirectory for files used by the HTML file will have the time-date stamp of the run of XCOPY. So, when sorting the copy on time date stamps, all the subdirectories, the HTML files and the corresponding subdirectories, e.g.,

x.htm

x_files

can appear far apart in the sort on time-date.

Hierarchical file systems go way back, IIRC to Multics at MIT in 1969, and since then lots of people have recognized the two cases, given a directory X, (i) copy directory X and all its contents and (ii) copy all the contents of X but not directory X itself. Well, if only from the experiments, XCOPY does only (ii).

So, the results of the 10 cases are below. For each case, in the results the first three lines have the first three arguments to XCOPY. So, the first line has the tree name of the directory to be copied, the 'source'; the second line has the tree name of the directory to get the copies, the 'destination', and the third line has the options for XCOPY. The remaining 1-2 lines have the results of the run of XCOPY.

One big point about the options is that options /X and /O result in result

Access denied

To see this, compare case 8 with the other cases that were the same, did not have /X and /O, but did copy.

These experiments have me better understand XCOPY and contribute an answer to the original question.

======= case 1 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_1\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 2 ==================
"k:\software\dir_time-date\*"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_2\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 3 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_3\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 4 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_4\"
options = /E /F /G /H /K /R /V /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 5 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_5\"
options = /E /F /G /H /K /O /R /S /X /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 6 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_6\"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 7 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_7"
options = /E /F /G /H /I /K /R /S /Y
Result:  20 File(s) copied
======= case 8 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_8"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 9 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_9"
options = /I /S
Result:  20 File(s) copied
======= case 10 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_10"
options = /E /I /S
Result:  20 File(s) copied

MySQL - UPDATE query with LIMIT

You should highly consider using an ORDER BY if you intend to LIMIT your UPDATE, because otherwise it will update in the ordering of the table, which might not be correct.

But as Will A said, it only allows limit on row_count, not offset.

Return row of Data Frame based on value in a column - R

@Zelazny7's answer works, but if you want to keep ties you could do:

df[which(df$Amount == min(df$Amount)), ]

For example with the following data frame:

df <- data.frame(Name = c("A", "B", "C", "D", "E"), 
                 Amount = c(150, 120, 175, 160, 120))

df[which.min(df$Amount), ]
#   Name Amount
# 2    B    120

df[which(df$Amount == min(df$Amount)), ]
#   Name Amount
# 2    B    120
# 5    E    120

Edit: If there are NAs in the Amount column you can do:

df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]

Quickly create a large file on a Linux system

truncate -s 10M output.file

will create a 10 M file instantaneously (M stands for 10241024 bytes, MB stands for 10001000 - same with K, KB, G, GB...)

EDIT: as many have pointed out, this will not physically allocate the file on your device. With this you could actually create an arbitrary large file, regardless of the available space on the device, as it creates a "sparse" file.

For e.g. notice no HDD space is consumed with this command:

### BEFORE
$ df -h | grep lvm
/dev/mapper/lvm--raid0-lvm0
                      7.2T  6.6T  232G  97% /export/lvm-raid0

$ truncate -s 500M 500MB.file

### AFTER
$ df -h | grep lvm
/dev/mapper/lvm--raid0-lvm0
                      7.2T  6.6T  232G  97% /export/lvm-raid0

So, when doing this, you will be deferring physical allocation until the file is accessed. If you're mapping this file to memory, you may not have the expected performance.

But this is still a useful command to know. For e.g. when benchmarking transfers using files, the specified size of the file will still get moved.

$ rsync -aHAxvP --numeric-ids --delete --info=progress2 \
       [email protected]:/export/lvm-raid0/500MB.file \
       /export/raid1/
receiving incremental file list
500MB.file
    524,288,000 100%   41.40MB/s    0:00:12 (xfr#1, to-chk=0/1)

sent 30 bytes  received 524,352,082 bytes  38,840,897.19 bytes/sec
total size is 524,288,000  speedup is 1.00

PHP find difference between two datetimes

The code below will show difference for found values only, i.e., if years = 0, then it will not show years.


$diffs = [
    'years' => 'y',
    'months' => 'm',
    'days' => 'd',
    'hours' => 'h',
    'minutes' => 'i',
    'seconds' => 's'
];

$interval = $timeout->diff($timein);
$diffArr = [];
foreach ($diffs as $k => $v) {
    $d = $interval->format('%' . $v);
    if ($d > 0) {
        $diffArr[] = $d . ' ' . $k;
    }
}    
$diffStr = implode(', ', $diffArr);
echo 'Difference: ' . ($diffStr == '' ? '0' : $diffStr) . PHP_EOL;

Can't install any package with node npm

I had this issue, and doing npm cache clean solved it.

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

`require': no such file to load -- mkmf (LoadError)

Have you tried:

sudo apt-get install ruby1.8-dev

What does the Excel range.Rows property really do?

Your two examples are the only things I have ever used the Rows and Columns properties for, but in theory you could do anything with them that can be done with a Range object.

The return type of those properties is itself a Range, so you can do things like:

Dim myRange as Range
Set myRange = Sheet1.Range(Cells(2,2),Cells(8,8))
myRange.Rows(3).Select

Which will select the third row in myRange (Cells B4:H4 in Sheet1).

update: To do what you want to do, you could use:

Dim interestingRows as Range
Set interestingRows = Sheet1.Range(startRow & ":" & endRow)

update #2: Or, to get a subset of rows from within a another range:

Dim someRange As Range
Dim interestingRows As Range

Set myRange = Sheet1.Range(Cells(2, 2), Cells(8, 8))

startRow = 3
endRow = 6

Set interestingRows = Range(myRange.Rows(startRow), myRange.Rows(endRow))

Linux find and grep command together

Now that the question is clearer, you can just do this in one

grep -R --include "*bills*" "put" .

With relevant flags

   -R, -r, --recursive
          Read  all  files  under  each  directory,  recursively;  this is
          equivalent to the -d recurse option.
   --include=GLOB
          Search only files whose base name matches GLOB  (using  wildcard
          matching as described under --exclude).

Plot a horizontal line using matplotlib

If you want to draw a horizontal line in the axes, you might also try ax.hlines() method. You need to specify y position and xmin and xmax in the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 21, 200)
y = np.exp(-x)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')

plt.show()

The snippet above will plot a horizontal line in the axes at y=0.2. The horizontal line starts at x=4 and ends at x=20. The generated image is:

enter image description here

How do I set GIT_SSL_NO_VERIFY for specific repos only?

If you are on a Windows machine and have the Git installed, you can try the below steps:

  1. Go to the folder of Git installation, ex: C:\Program Files (x86)\Git\etc
  2. Edit the file: gitconfig
  3. Under the [http] section, add the line: sslVerify = false

    [http]
      sslVerify = false
    

How do I get current scope dom-element in AngularJS controller?

In controller:

function innerItem($scope, $element){
    var jQueryInnerItem = $($element); 
}

A simple explanation of Naive Bayes Classification

I try to explain the Bayes rule with an example.

What is the chance that a random person selected from the society is a smoker?

You may reply 10%, and let's assume that's right.

Now, what if I say that the random person is a man and is 15 years old?

You may say 15 or 20%, but why?.

In fact, we try to update our initial guess with new pieces of evidence ( P(smoker) vs. P(smoker | evidence) ). The Bayes rule is a way to relate these two probabilities.

P(smoker | evidence) = P(smoker)* p(evidence | smoker)/P(evidence)

Each evidence may increase or decrease this chance. For example, this fact that he is a man may increase the chance provided that this percentage (being a man) among non-smokers is lower.

In the other words, being a man must be an indicator of being a smoker rather than a non-smoker. Therefore, if an evidence is an indicator of something, it increases the chance.

But how do we know that this is an indicator?

For each feature, you can compare the commonness (probability) of that feature under the given conditions with its commonness alone. (P(f | x) vs. P(f)).

P(smoker | evidence) / P(smoker) = P(evidence | smoker)/P(evidence)

For example, if we know that 90% of smokers are men, it's not still enough to say whether being a man is an indicator of being smoker or not. For example if the probability of being a man in the society is also 90%, then knowing that someone is a man doesn't help us ((90% / 90%) = 1. But if men contribute to 40% of the society, but 90% of the smokers, then knowing that someone is a man increases the chance of being a smoker (90% / 40%) = 2.25, so it increases the initial guess (10%) by 2.25 resulting 22.5%.

However, if the probability of being a man was 95% in the society, then regardless of the fact that the percentage of men among smokers is high (90%)! the evidence that someone is a man decreases the chance of him being a smoker! (90% / 95%) = 0.95).

So we have:

P(smoker | f1, f2, f3,... ) = P(smoker) * contribution of f1* contribution of f2 *... 
=
P(smoker)* 
(P(being a man | smoker)/P(being a man))*
(P(under 20 | smoker)/ P(under 20))

Note that in this formula we assumed that being a man and being under 20 are independent features so we multiplied them, it means that knowing that someone is under 20 has no effect on guessing that he is man or woman. But it may not be true, for example maybe most adolescence in a society are men...

To use this formula in a classifier

The classifier is given with some features (being a man and being under 20) and it must decide if he is an smoker or not (these are two classes). It uses the above formula to calculate the probability of each class under the evidence (features), and it assigns the class with the highest probability to the input. To provide the required probabilities (90%, 10%, 80%...) it uses the training set. For example, it counts the people in the training set that are smokers and find they contribute 10% of the sample. Then for smokers checks how many of them are men or women .... how many are above 20 or under 20....In the other words, it tries to build the probability distribution of the features for each class based on the training data.

Modify tick label text

The axes class has a set_yticklabels function which allows you to set the tick labels, like so:

#ax is the axes instance
group_labels = ['control', 'cold treatment',
             'hot treatment', 'another treatment',
             'the last one']

ax.set_xticklabels(group_labels)

I'm still working on why your example above didn't work.

Force DOM redraw/refresh on Chrome/Mac

call window.getComputedStyle() should force a reflow

excel plot against a date time x series

[excel 2010] separate the date and time into separate columns and select both as X-Axis and data as graph series see http://www.79783.mrsite.com/USERIMAGES/horizontal_axis_date_and_time2.xlsx

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

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

How can I delete a newline if it is the last character in a file?

gawk

   awk '{q=p;p=$0}NR>1{print q}END{ORS = ""; print p}' file

How to sort a data frame by alphabetic order of a character variable in R?

The order() function fails when the column has levels or factor. It works properly when stringsAsFactors=FALSE is used in data.frame creation.

Delete all rows with timestamp older than x days

DELETE FROM on_search WHERE search_date < NOW() - INTERVAL N DAY

Replace N with your day count

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

in my case, the error was with www-data user but not with normal user on development. The error was a problem to initialize an x display for this user. So, the problem was resolved running my selenium test without opening a browser window, headless:

opts.set_headless(True)

How to concat string + i?

Try the following:

for i = 1:4
    result = strcat('f',int2str(i));
end

If you use this for naming several files that your code generates, you are able to concatenate more parts to the name. For example, with the extension at the end and address at the beginning:

filename = strcat('c:\...\name',int2str(i),'.png'); 

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

Just to add to what Cade said, this is usually a front-end display thing and should therefore be handled there. I know that sometimes it's easier to write something 100% in SQL for things like file export or other "SQL only" solutions, but most of the times this concatenation should be handled in your display layer.

How can I display the current branch and folder path in terminal?

My prompt includes:

  • Exit status of last command (if not 0)
  • Distinctive changes when root
  • rsync-style user@host:pathname for copy-paste goodness
  • Git branch, index, modified, untracked and upstream information
  • Pretty colours

Example: Screenshot of my prompt in action To do this, add the following to your ~/.bashrc:

#
# Set the prompt #
#

# Select git info displayed, see /usr/share/git/completion/git-prompt.sh for more
export GIT_PS1_SHOWDIRTYSTATE=1           # '*'=unstaged, '+'=staged
export GIT_PS1_SHOWSTASHSTATE=1           # '$'=stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1       # '%'=untracked
export GIT_PS1_SHOWUPSTREAM="verbose"     # 'u='=no difference, 'u+1'=ahead by 1 commit
export GIT_PS1_STATESEPARATOR=''          # No space between branch and index status
export GIT_PS1_DESCRIBE_STYLE="describe"  # detached HEAD style:
#  contains      relative to newer annotated tag (v1.6.3.2~35)
#  branch        relative to newer tag or branch (master~4)
#  describe      relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
#  default       exactly eatching tag

# Check if we support colours
__colour_enabled() {
    local -i colors=$(tput colors 2>/dev/null)
    [[ $? -eq 0 ]] && [[ $colors -gt 2 ]]
}
unset __colourise_prompt && __colour_enabled && __colourise_prompt=1

__set_bash_prompt()
{
    local exit="$?" # Save the exit status of the last command

    # PS1 is made from $PreGitPS1 + <git-status> + $PostGitPS1
    local PreGitPS1="${debian_chroot:+($debian_chroot)}"
    local PostGitPS1=""

    if [[ $__colourise_prompt ]]; then
        export GIT_PS1_SHOWCOLORHINTS=1

        # Wrap the colour codes between \[ and \], so that
        # bash counts the correct number of characters for line wrapping:
        local Red='\[\e[0;31m\]'; local BRed='\[\e[1;31m\]'
        local Gre='\[\e[0;32m\]'; local BGre='\[\e[1;32m\]'
        local Yel='\[\e[0;33m\]'; local BYel='\[\e[1;33m\]'
        local Blu='\[\e[0;34m\]'; local BBlu='\[\e[1;34m\]'
        local Mag='\[\e[0;35m\]'; local BMag='\[\e[1;35m\]'
        local Cya='\[\e[0;36m\]'; local BCya='\[\e[1;36m\]'
        local Whi='\[\e[0;37m\]'; local BWhi='\[\e[1;37m\]'
        local None='\[\e[0m\]' # Return to default colour

        # No username and bright colour if root
        if [[ ${EUID} == 0 ]]; then
            PreGitPS1+="$BRed\h "
        else
            PreGitPS1+="$Red\u@\h$None:"
        fi

        PreGitPS1+="$Blu\w$None"
    else # No colour
        # Sets prompt like: ravi@boxy:~/prj/sample_app
        unset GIT_PS1_SHOWCOLORHINTS
        PreGitPS1="${debian_chroot:+($debian_chroot)}\u@\h:\w"
    fi

    # Now build the part after git's status

    # Highlight non-standard exit codes
    if [[ $exit != 0 ]]; then
        PostGitPS1="$Red[$exit]"
    fi

    # Change colour of prompt if root
    if [[ ${EUID} == 0 ]]; then
        PostGitPS1+="$BRed"'\$ '"$None"
    else
        PostGitPS1+="$Mag"'\$ '"$None"
    fi

    # Set PS1 from $PreGitPS1 + <git-status> + $PostGitPS1
    __git_ps1 "$PreGitPS1" "$PostGitPS1" '(%s)'

    # echo '$PS1='"$PS1" # debug    
    # defaut Linux Mint 17.2 user prompt:
    # PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\] $(__git_ps1 "(%s)") \$ '
}

# This tells bash to reinterpret PS1 after every command, which we
# need because __git_ps1 will return different text and colors
PROMPT_COMMAND=__set_bash_prompt

How to add a second x-axis in matplotlib

I'm forced to post this as an answer instead of a comment due to low reputation. I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:

ax2.lines = []

instead of using:

ax2.cla()

When in use also cleared my plot from ax1.

How to dump a dict to a json file?

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...

What is difference between monolithic and micro kernel?

Microkernel:

Moves as much from the kernel into “user” space.

Communication takes place between user modules using message passing.

Benefits:

1-Easier to extend a microkernel

2-Easier to port the operating system to new architectures

3-More reliable (less code is running in kernel mode)

4-More secure

Detriments:

1-Performance overhead of user space to kernel space communication

How to get first and last element in an array in java?

This is the given array.

    int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};

// If you want print the last element in the array.

    int lastNumerOfArray= myIntegerNumbers[9];
    Log.i("MyTag", lastNumerOfArray + "");

// If you want to print the number of element in the array.

    Log.i("MyTag", "The number of elements inside" +
            "the array " +myIntegerNumbers.length);

// Second method to print the last element inside the array.

    Log.i("MyTag", "The last elements inside " +
            "the array " + myIntegerNumbers[myIntegerNumbers.length-1]);

ASP.NET MVC DropDownListFor with model of type List<string>

To make a dropdown list you need two properties:

  1. a property to which you will bind to (usually a scalar property of type integer or string)
  2. a list of items containing two properties (one for the values and one for the text)

In your case you only have a list of string which cannot be exploited to create a usable drop down list.

While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:

@model List<string>
@Html.DropDownList(
    "Foo", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    )
)

where Foo will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:

<select name="Foo" id="Foo">
    <option value="item 1">item 1</option>
    <option value="item 2">item 2</option>
    <option value="item 3">item 3</option>
    ...
</select>

This being said a far better view model for a drop down list is the following:

public class MyListModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then:

@model MyListModel
@Html.DropDownListFor(
    x => x.SelectedItemId,
    new SelectList(Model.Items, "Value", "Text")
)

and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId property of this view model to the corresponding Value of some element in the Items collection.

Android: Cancel Async Task

Most of the time that I use AsyncTask my business logic is on a separated business class instead of being on the UI. In that case, I couldn't have a loop at doInBackground(). An example would be a synchronization process that consumes services and persist data one after another.

I end up handing on my task to the business object so it can handle cancelation. My setup is like this:

public abstract class MyActivity extends Activity {

    private Task mTask;
    private Business mBusiness;

    public void startTask() {
        if (mTask != null) {
            mTask.cancel(true);
        }
        mTask = new mTask();
        mTask.execute();
    }
}

protected class Task extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected void onCancelled() {
        super.onCancelled();

        mTask.cancel(true);

        // ask if user wants to try again
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        return mBusiness.synchronize(this);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        mTask = null;

        if (result) {
            // done!
        }
        else {
            // ask if user wants to try again
        }
    }
}

public class Business {
    public boolean synchronize(AsyncTask<?, ?, ?> task) {
        boolean response = false;
        response = loadStuff(task);

        if (response)
            response = loadMoreStuff(task);

        return response;
    }

    private boolean loadStuff(AsyncTask<?, ?, ?> task) {
        if (task != null && task.isCancelled()) return false;

        // load stuff

        return true;
    }
}

Oracle SqlDeveloper JDK path

another thing you could try is to rename your old jdk folder, lets say its:

C:\Program Files\Java\jdk1.7.0_04

change it to saomething like:

C:\Program Files\Java\xxxjdk1.7.0_04

Now, you should once again asked to set your jdk folder location on Oracle SqlDeveloper launch, and you can chose the right path.

Not the most elegant solution, but it worked for me.

Milos

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

How to pass multiple parameters from ajax to mvc controller?

Try this:

var req={StrContactDetails:'data',IsPrimary:'True'}

$.ajax({
                   type: 'POST',
                   data: req,
                   url: '@url.Action("SaveEmergencyContact","Dhp")',
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   data: JSON.stringify(req),
                   success: function (data) {
                       alert("Success");
                   },
                   error: function (ob, errStr) {
                       alert("An error occured.Please try after sometime.");
                   }
               });

http://api.jquery.com/jquery.ajax/

.Net System.Mail.Message adding multiple "To" addresses

I wasn't able to replicate your bug:

var message = new MailMessage();

message.To.Add("[email protected]");
message.To.Add("[email protected]");

message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.Body = "Test";

var client = new SmtpClient("localhost", 25);
client.Send(message);

Dumping the contents of the To: MailAddressCollection:

MailAddressCollection (2 items)
DisplayName User Host Address

user example.com [email protected]
user2 example.com [email protected]

And the resulting e-mail as caught by smtp4dev:

Received: from mycomputername (mycomputername [127.0.0.1])
     by localhost (Eric Daugherty's C# Email Server)
     3/8/2010 12:50:28 PM
MIME-Version: 1.0
From: [email protected]
To: [email protected], [email protected]
Date: 8 Mar 2010 12:50:28 -0800
Subject: Test
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

Test

Are you sure there's not some other issue going on with your code or SMTP server?

Space between two divs

DIVs inherently lack any useful meaning, other than to divide, of course.

Best course of action would be to add a meaningful class name to them, and style their individual margins in CSS.

<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>

h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}

Is it possible to declare a public variable in vba and assign a default value?

As told above, To declare global accessible variables you can do it outside functions preceded with the public keyword.

And, since the affectation is NOT PERMITTED outside the procedures, you can, for example, create a sub called InitGlobals that initializes your public variables, then you just call this subroutine at the beginning of your statements

Here is an example of it:

Public Coordinates(3) as Double
Public Heat as double
Public Weight as double

Sub InitGlobals()
    Coordinates(1)=10.5
    Coordinates(2)=22.54
    Coordinates(3)=-100.5
    Heat=25.5
    Weight=70
End Sub

Sub MyWorkSGoesHere()
    Call InitGlobals
    'Now you can do your work using your global variables initialized as you wanted them to be.
End Sub

Converting a string to a date in DB2

I know its old post but still I want to contribute
Above will not work if you have data format like this
'YYYMMDD'

For example:

Dt
20151104

So I tried following in order to get the desired result.

select cast(Left('20151104', 4)||'-'||substring('20151104',5,2)||'-'||substring('20151104', 7,2) as date) from SYSIBM.SYSDUMMY1;

Additionally, If you want to run the query from MS SQL linked server to DB2(To display only 100 rows).

    SELECT top 100 * from OPENQUERY([Linked_Server_Name],
    'select cast(Left(''20151104'', 4)||''-''||substring(''20151104'',5,2)||''-''||substring(''20151104'', 7,2) as date) AS Dt 
    FROM SYSIBM.SYSDUMMY1')

Result after above query:

Dt
2015-11-04

Hope this helps for others.

Android Studio - No JVM Installation found

My fix was to remove the double quotes that I had enclosed the JAVA_HOME path in.

Instead of declaring JAVA_HOME as "C\Program Files..."

I removed the " and declared JAVA_HOME as C\Program Files...

I am on Win 7, x64

Is it possible to have empty RequestParam values use the defaultValue?

You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
    if(i == null) {
        i = 10;
    }
    // ...
}

I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:

http://example.com/test

CSV with comma or semicolon?

In Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.

Of course this only has effect in Windows applications, for example Excel will not automatically split data into columns if the file is not using the above mentioned separator. All applications that use Windows regional settings will have this behavior.

If you are writing a program for Windows that will require importing the CSV in other applications and you know that the list separator set for your target machines is ,, then go for it, otherwise I prefer ; since it causes less problems with decimal points, digit grouping and does not appear in much text.

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]
    }

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)
    }

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print(bike.name + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

Psql list all tables

A one-line example is

\dt schemaname.* 

in your senario

\dt public.*

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

Rounding a double value to x number of decimal places in swift

This seems to work in Swift 5.

Quite surprised there isn't a standard function for this already.

//Truncation of Double to n-decimal places with rounding

extension Double {

    func truncate(to places: Int) -> Double {
    return Double(Int((pow(10, Double(places)) * self).rounded())) / pow(10, Double(places))
    }

}

pandas convert some columns into rows

pd.wide_to_long

You can add a prefix to your year columns and then feed directly to pd.wide_to_long. I won't pretend this is efficient, but it may in certain situations be more convenient than pd.melt, e.g. when your columns already have an appropriate prefix.

df.columns = np.hstack((df.columns[:2], df.columns[2:].map(lambda x: f'Value{x}')))

res = pd.wide_to_long(df, stubnames=['Value'], i='name', j='Date').reset_index()\
        .sort_values(['location', 'name'])

print(res)

   name        Date location  Value
0  test    Jan-2010        A     12
2  test    Feb-2010        A     20
4  test  March-2010        A     30
1   foo    Jan-2010        B     18
3   foo    Feb-2010        B     20
5   foo  March-2010        B     25

Shuffle DataFrame rows

AFAIK the simplest solution is:

df_shuffled = df.reindex(np.random.permutation(df.index))

How does MySQL CASE work?

I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even

SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

Your most elegant solution must be:

var left: Node? = null

fun show() {
    left?.also {
        queue.add( it )
    }
}

Then you don't have to define a new and unnecessary local variable, and you don't have any new assertions or casts (which are not DRY). Other scope functions could also work so choose your favourite.

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
|   value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+

df_split = df.select(f.split(df.value,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])

df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|
+----+----+----+

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

What is the best way to delete a value from an array in Perl?

splice will remove array element(s) by index. Use grep, as in your example, to search and remove.

Javascript onload not working

You can try use in javascript:

window.onload = function() {
 alert("let's go!");
}

Its a good practice separate javascript of html

How do function pointers in C work?

A function pointer is a variable that contains the address of a function. Since it is a pointer variable though with some restricted properties, you can use it pretty much like you would any other pointer variable in data structures.

The only exception I can think of is treating the function pointer as pointing to something other than a single value. Doing pointer arithmetic by incrementing or decrementing a function pointer or adding/subtracting an offset to a function pointer isn't really of any utility as a function pointer only points to a single thing, the entry point of a function.

The size of a function pointer variable, the number of bytes occupied by the variable, may vary depending on the underlying architecture, e.g. x32 or x64 or whatever.

The declaration for a function pointer variable needs to specify the same kind of information as a function declaration in order for the C compiler to do the kinds of checks that it normally does. If you don't specify a parameter list in the declaration/definition of the function pointer, the C compiler will not be able to check the use of parameters. There are cases when this lack of checking can be useful however just remember that a safety net has been removed.

Some examples:

int func (int a, char *pStr);    // declares a function

int (*pFunc)(int a, char *pStr);  // declares or defines a function pointer

int (*pFunc2) ();                 // declares or defines a function pointer, no parameter list specified.

int (*pFunc3) (void);             // declares or defines a function pointer, no arguments.

The first two declararations are somewhat similar in that:

  • func is a function that takes an int and a char * and returns an int
  • pFunc is a function pointer to which is assigned the address of a function that takes an int and a char * and returns an int

So from the above we could have a source line in which the address of the function func() is assigned to the function pointer variable pFunc as in pFunc = func;.

Notice the syntax used with a function pointer declaration/definition in which parenthesis are used to overcome the natural operator precedence rules.

int *pfunc(int a, char *pStr);    // declares a function that returns int pointer
int (*pFunc)(int a, char *pStr);  // declares a function pointer that returns an int

Several Different Usage Examples

Some examples of usage of a function pointer:

int (*pFunc) (int a, char *pStr);    // declare a simple function pointer variable
int (*pFunc[55])(int a, char *pStr); // declare an array of 55 function pointers
int (**pFunc)(int a, char *pStr);    // declare a pointer to a function pointer variable
struct {                             // declare a struct that contains a function pointer
    int x22;
    int (*pFunc)(int a, char *pStr);
} thing = {0, func};                 // assign values to the struct variable
char * xF (int x, int (*p)(int a, char *pStr));  // declare a function that has a function pointer as an argument
char * (*pxF) (int x, int (*p)(int a, char *pStr));  // declare a function pointer that points to a function that has a function pointer as an argument

You can use variable length parameter lists in the definition of a function pointer.

int sum (int a, int b, ...);
int (*psum)(int a, int b, ...);

Or you can not specify a parameter list at all. This can be useful but it eliminates the opportunity for the C compiler to perform checks on the argument list provided.

int  sum ();      // nothing specified in the argument list so could be anything or nothing
int (*psum)();
int  sum2(void);  // void specified in the argument list so no parameters when calling this function
int (*psum2)(void);

C style Casts

You can use C style casts with function pointers. However be aware that a C compiler may be lax about checks or provide warnings rather than errors.

int sum (int a, char *b);
int (*psplsum) (int a, int b);
psplsum = sum;               // generates a compiler warning
psplsum = (int (*)(int a, int b)) sum;   // no compiler warning, cast to function pointer
psplsum = (int *(int a, int b)) sum;     // compiler error of bad cast generated, parenthesis are required.

Compare Function Pointer to Equality

You can check that a function pointer is equal to a particular function address using an if statement though I am not sure how useful that would be. Other comparison operators would seem to have even less utility.

static int func1(int a, int b) {
    return a + b;
}

static int func2(int a, int b, char *c) {
    return c[0] + a + b;
}

static int func3(int a, int b, char *x) {
    return a + b;
}

static char *func4(int a, int b, char *c, int (*p)())
{
    if (p == func1) {
        p(a, b);
    }
    else if (p == func2) {
        p(a, b, c);      // warning C4047: '==': 'int (__cdecl *)()' differs in levels of indirection from 'char *(__cdecl *)(int,int,char *)'
    } else if (p == func3) {
        p(a, b, c);
    }
    return c;
}

An Array of Function Pointers

And if you want to have an array of function pointers each of the elements of which the argument list has differences then you can define a function pointer with the argument list unspecified (not void which means no arguments but just unspecified) something like the following though you may see warnings from the C compiler. This also works for a function pointer parameter to a function:

int(*p[])() = {       // an array of function pointers
    func1, func2, func3
};
int(**pp)();          // a pointer to a function pointer


p[0](a, b);
p[1](a, b, 0);
p[2](a, b);      // oops, left off the last argument but it compiles anyway.

func4(a, b, 0, func1);
func4(a, b, 0, func2);  // warning C4047: 'function': 'int (__cdecl *)()' differs in levels of indirection from 'char *(__cdecl *)(int,int,char *)'
func4(a, b, 0, func3);

    // iterate over the array elements using an array index
for (i = 0; i < sizeof(p) / sizeof(p[0]); i++) {
    func4(a, b, 0, p[i]);
}
    // iterate over the array elements using a pointer
for (pp = p; pp < p + sizeof(p)/sizeof(p[0]); pp++) {
    (*pp)(a, b, 0);          // pointer to a function pointer so must dereference it.
    func4(a, b, 0, *pp);     // pointer to a function pointer so must dereference it.
}

C style namespace Using Global struct with Function Pointers

You can use the static keyword to specify a function whose name is file scope and then assign this to a global variable as a way of providing something similar to the namespace functionality of C++.

In a header file define a struct that will be our namespace along with a global variable that uses it.

typedef struct {
   int (*func1) (int a, int b);             // pointer to function that returns an int
   char *(*func2) (int a, int b, char *c);  // pointer to function that returns a pointer
} FuncThings;

extern const FuncThings FuncThingsGlobal;

Then in the C source file:

#include "header.h"

// the function names used with these static functions do not need to be the
// same as the struct member names. It's just helpful if they are when trying
// to search for them.
// the static keyword ensures these names are file scope only and not visible
// outside of the file.
static int func1 (int a, int b)
{
    return a + b;
}

static char *func2 (int a, int b, char *c)
{
    c[0] = a % 100; c[1] = b % 50;
    return c;
}

const FuncThings FuncThingsGlobal = {func1, func2};

This would then be used by specifying the complete name of global struct variable and member name to access the function. The const modifier is used on the global so that it can not be changed by accident.

int abcd = FuncThingsGlobal.func1 (a, b);

Application Areas of Function Pointers

A DLL library component could do something similar to the C style namespace approach in which a particular library interface is requested from a factory method in a library interface which supports the creation of a struct containing function pointers.. This library interface loads the requested DLL version, creates a struct with the necessary function pointers, and then returns the struct to the requesting caller for use.

typedef struct {
    HMODULE  hModule;
    int (*Func1)();
    int (*Func2)();
    int(*Func3)(int a, int b);
} LibraryFuncStruct;

int  LoadLibraryFunc LPCTSTR  dllFileName, LibraryFuncStruct *pStruct)
{
    int  retStatus = 0;   // default is an error detected

    pStruct->hModule = LoadLibrary (dllFileName);
    if (pStruct->hModule) {
        pStruct->Func1 = (int (*)()) GetProcAddress (pStruct->hModule, "Func1");
        pStruct->Func2 = (int (*)()) GetProcAddress (pStruct->hModule, "Func2");
        pStruct->Func3 = (int (*)(int a, int b)) GetProcAddress(pStruct->hModule, "Func3");
        retStatus = 1;
    }

    return retStatus;
}

void FreeLibraryFunc (LibraryFuncStruct *pStruct)
{
    if (pStruct->hModule) FreeLibrary (pStruct->hModule);
    pStruct->hModule = 0;
}

and this could be used as in:

LibraryFuncStruct myLib = {0};
LoadLibraryFunc (L"library.dll", &myLib);
//  ....
myLib.Func1();
//  ....
FreeLibraryFunc (&myLib);

The same approach can be used to define an abstract hardware layer for code that uses a particular model of the underlying hardware. Function pointers are filled in with hardware specific functions by a factory to provide the hardware specific functionality that implements functions specified in the abstract hardware model. This can be used to provide an abstract hardware layer used by software which calls a factory function in order to get the specific hardware function interface then uses the function pointers provided to perform actions for the underlying hardware without needing to know implementation details about the specific target.

Function Pointers to create Delegates, Handlers, and Callbacks

You can use function pointers as a way to delegate some task or functionality. The classic example in C is the comparison delegate function pointer used with the Standard C library functions qsort() and bsearch() to provide the collation order for sorting a list of items or performing a binary search over a sorted list of items. The comparison function delegate specifies the collation algorithm used in the sort or the binary search.

Another use is similar to applying an algorithm to a C++ Standard Template Library container.

void * ApplyAlgorithm (void *pArray, size_t sizeItem, size_t nItems, int (*p)(void *)) {
    unsigned char *pList = pArray;
    unsigned char *pListEnd = pList + nItems * sizeItem;
    for ( ; pList < pListEnd; pList += sizeItem) {
        p (pList);
    }

    return pArray;
}

int pIncrement(int *pI) {
    (*pI)++;

    return 1;
}

void * ApplyFold(void *pArray, size_t sizeItem, size_t nItems, void * pResult, int(*p)(void *, void *)) {
    unsigned char *pList = pArray;
    unsigned char *pListEnd = pList + nItems * sizeItem;
    for (; pList < pListEnd; pList += sizeItem) {
        p(pList, pResult);
    }

    return pArray;
}

int pSummation(int *pI, int *pSum) {
    (*pSum) += *pI;

    return 1;
}

// source code and then lets use our function.
int intList[30] = { 0 }, iSum = 0;

ApplyAlgorithm(intList, sizeof(int), sizeof(intList) / sizeof(intList[0]), pIncrement);
ApplyFold(intList, sizeof(int), sizeof(intList) / sizeof(intList[0]), &iSum, pSummation);

Another example is with GUI source code in which a handler for a particular event is registered by providing a function pointer which is actually called when the event happens. The Microsoft MFC framework with its message maps uses something similar to handle Windows messages that are delivered to a window or thread.

Asynchronous functions that require a callback are similar to an event handler. The user of the asynchronous function calls the asynchronous function to start some action and provides a function pointer which the asynchronous function will call once the action is complete. In this case the event is the asynchronous function completing its task.

Possible to make labels appear when hovering over a point in matplotlib?

It seems none of the other answers here actually answer the question. So here is a code that uses a scatter and shows an annotation upon hovering over the scatter points.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)

annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def update_annot(ind):

    pos = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), 
                           " ".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()

enter image description here

Because people also want to use this solution for a line plot instead of a scatter, the following would be the same solution for plot (which works slightly differently).

_x000D_
_x000D_
import matplotlib.pyplot as plt_x000D_
import numpy as np; np.random.seed(1)_x000D_
_x000D_
x = np.sort(np.random.rand(15))_x000D_
y = np.sort(np.random.rand(15))_x000D_
names = np.array(list("ABCDEFGHIJKLMNO"))_x000D_
_x000D_
norm = plt.Normalize(1,4)_x000D_
cmap = plt.cm.RdYlGn_x000D_
_x000D_
fig,ax = plt.subplots()_x000D_
line, = plt.plot(x,y, marker="o")_x000D_
_x000D_
annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",_x000D_
                    bbox=dict(boxstyle="round", fc="w"),_x000D_
                    arrowprops=dict(arrowstyle="->"))_x000D_
annot.set_visible(False)_x000D_
_x000D_
def update_annot(ind):_x000D_
    x,y = line.get_data()_x000D_
    annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])_x000D_
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), _x000D_
                           " ".join([names[n] for n in ind["ind"]]))_x000D_
    annot.set_text(text)_x000D_
    annot.get_bbox_patch().set_alpha(0.4)_x000D_
_x000D_
_x000D_
def hover(event):_x000D_
    vis = annot.get_visible()_x000D_
    if event.inaxes == ax:_x000D_
        cont, ind = line.contains(event)_x000D_
        if cont:_x000D_
            update_annot(ind)_x000D_
            annot.set_visible(True)_x000D_
            fig.canvas.draw_idle()_x000D_
        else:_x000D_
            if vis:_x000D_
                annot.set_visible(False)_x000D_
                fig.canvas.draw_idle()_x000D_
_x000D_
fig.canvas.mpl_connect("motion_notify_event", hover)_x000D_
_x000D_
plt.show()
_x000D_
_x000D_
_x000D_

In case someone is looking for a solution for lines in twin axes, refer to How to make labels appear when hovering over a point in multiple axis?

In case someone is looking for a solution for bar plots, please refer to e.g. this answer.

Prepend line to beginning of a file

To put code to NPE's answer, I think the most efficient way to do this is:

def insert(originalfile,string):
    with open(originalfile,'r') as f:
        with open('newfile.txt','w') as f2: 
            f2.write(string)
            f2.write(f.read())
    os.rename('newfile.txt',originalfile)

How do I increase modal width in Angular UI Bootstrap?

If you want to just go with the default large size you can add 'modal-lg':

var modal = $modal.open({
          templateUrl: "/partials/welcome",
          controller: "welcomeCtrl",
          backdrop: "static",
          scope: $scope,
          windowClass: 'modal-lg'
});

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

LL(1) grammar is Context free unambiguous grammar which can be parsed by LL(1) parsers.

In LL(1)

  • First L stands for scanning input from Left to Right. Second L stands for Left Most Derivation. 1 stands for using one input symbol at each step.

For Checking grammar is LL(1) you can draw predictive parsing table. And if you find any multiple entries in table then you can say grammar is not LL(1).

Their is also short cut to check if the grammar is LL(1) or not . Shortcut Technique

Postgresql: password authentication failed for user "postgres"

When you install postgresql no password is set for user postgres, you have to explicitly set it on Unix by using the command:

sudo passwd postgres

It will ask your sudo password and then promt you for new postgres user password. Source

What is the cause for "angular is not defined"

You have not placed the script tags for angular js

you can do so by using cdn or downloading the angularjs for your project and then referencing it

after this you have to add your own java script in your case main.js

that should do

How do I get an Excel range using row and column numbers in VSTO / C#?

I found a good short method that seems to work well...

Dim x, y As Integer
x = 3: y = 5  
ActiveSheet.Cells(y, x).Select
ActiveCell.Value = "Tada"

In this example we are selecting 3 columns over and 5 rows down, then putting "Tada" in the cell.

How to open every file in a folder

You can actually just use os module to do both:

  1. list all files in a folder
  2. sort files by file type, file name etc.

Here's a simple example:

import os #os module imported here
location = os.getcwd() # get present working directory location here
counter = 0 #keep a count of all files found
csvfiles = [] #list to store all csv files found at location
filebeginwithhello = [] # list to keep all files that begin with 'hello'
otherfiles = [] #list to keep any other file that do not match the criteria

for file in os.listdir(location):
    try:
        if file.endswith(".csv"):
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello"):
            print "hello files found: \t", file
            filebeginwithhello.append(file)
            counter = counter+1

        else:
            otherfiles.append(file)
            counter = counter+1
    except Exception as e:
        raise e
        print "No files found here!"

print "Total files found:\t", counter

Now you have not only listed all the files in a folder but also have them (optionally) sorted by starting name, file type and others. Just now iterate over each list and do your stuff.

System.Net.WebException: The operation has timed out

I remember I had the same problem a while back using WCF due the quantity of the data I was passing. I remember I changed timeouts everywhere but the problem persisted. What I finally did was open the connection as stream request, I needed to change the client and the server side, but it work that way. Since it was a stream connection, the server kept reading until the stream ended.

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

if (($_SERVER['REQUEST_METHOD'] == 'POST') and (isset($_SESSION['uniq']))){
    if($everything_fine){
        unset($_SESSION['uniq']);
    }
}
else{
    $_SESSION['uniq'] = uniqid();
}

Problems when trying to load a package in R due to rJava

I had a similar problem what worked for me was to set JAVA_HOME. I tired it first in R:

Sys.setenv(JAVA_HOME = "C:/Program Files/Java/jdk1.8.0_101/")

And when it actually worked I set it in

System Properties -> Advanced -> Environment Variables

by adding a new System variable. I then restarted R/RStudio and everything worked.

Android: I am unable to have ViewPager WRAP_CONTENT

I have an version of WrapContentHeightViewPager that was working correctly before API 23 that will resize the parent view's height base on the current child view selected.

After upgrading to API 23, it stopped working. It turns out the old solution was using getChildAt(getCurrentItem()) to get the current child view to measure which is not working. See solution here: https://stackoverflow.com/a/16512217/1265583

Below works with API 23:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int height = 0;
    ViewPagerAdapter adapter = (ViewPagerAdapter)getAdapter();
    View child = adapter.getItem(getCurrentItem()).getView();
    if(child != null) {
        child.measure(widthMeasureSpec,  MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        height = child.getMeasuredHeight();
    }
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

List of IP addresses/hostnames from local network in Python

If by "local" you mean on the same network segment, then you have to perform the following steps:

  1. Determine your own IP address
  2. Determine your own netmask
  3. Determine the network range
  4. Scan all the addresses (except the lowest, which is your network address and the highest, which is your broadcast address).
  5. Use your DNS's reverse lookup to determine the hostname for IP addresses which respond to your scan.

Or you can just let Python execute nmap externally and pipe the results back into your program.

Eclipse Build Path Nesting Errors

I had the same problem even when I created a fresh project. I was creating the Java project within Eclipse, then mavenize it, then going into java build path properties removing src/ and adding src/main/java and src/test/java. When I run Maven update it used to give nested path error.
Then I finally realized -because I had not seen that entry before- there is a <sourceDirectory>src</sourceDirectory> line in pom file written when I mavenize it. It was resolved after removing it.

How to get WordPress post featured image URL

You can try this.

<?php
   $image_url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
<a href="<?php echo $image_url; ?>" rel="prettyPhoto">

Is it possible to move/rename files in Git and maintain their history?

While the core of Git, the Git plumbing doesn't keep track of renames, the history you display with the Git log "porcelain" can detect them if you like.

For a given git log use the -M option:

git log -p -M

With a current version of Git.

This works for other commands like git diff as well.

There are options to make the comparisons more or less rigorous. If you rename a file without making significant changes to the file at the same time it makes it easier for Git log and friends to detect the rename. For this reason some people rename files in one commit and change them in another.

There's a cost in CPU use whenever you ask Git to find where files have been renamed, so whether you use it or not, and when, is up to you.

If you would like to always have your history reported with rename detection in a particular repository you can use:

git config diff.renames 1

Files moving from one directory to another is detected. Here's an example:

commit c3ee8dfb01e357eba1ab18003be1490a46325992
Author: John S. Gruber <[email protected]>
Date:   Wed Feb 22 22:20:19 2017 -0500

    test rename again

diff --git a/yyy/power.py b/zzz/power.py
similarity index 100%
rename from yyy/power.py
rename to zzz/power.py

commit ae181377154eca800832087500c258a20c95d1c3
Author: John S. Gruber <[email protected]>
Date:   Wed Feb 22 22:19:17 2017 -0500

    rename test

diff --git a/power.py b/yyy/power.py
similarity index 100%
rename from power.py
rename to yyy/power.py

Please note that this works whenever you are using diff, not just with git log. For example:

$ git diff HEAD c3ee8df
diff --git a/power.py b/zzz/power.py
similarity index 100%
rename from power.py
rename to zzz/power.py

As a trial I made a small change in one file in a feature branch and committed it and then in the master branch I renamed the file, committed, and then made a small change in another part of the file and committed that. When I went to feature branch and merged from master the merge renamed the file and merged the changes. Here's the output from the merge:

 $ git merge -v master
 Auto-merging single
 Merge made by the 'recursive' strategy.
  one => single | 4 ++++
  1 file changed, 4 insertions(+)
  rename one => single (67%)

The result was a working directory with the file renamed and both text changes made. So it's possible for Git to do the right thing despite the fact that it doesn't explicitly track renames.

This is an late answer to an old question so the other answers may have been correct for the Git version at the time.

Difference between abstract class and interface in Python

What you'll see sometimes is the following:

class Abstract1( object ):
    """Some description that tells you it's abstract,
    often listing the methods you're expected to supply."""
    def aMethod( self ):
        raise NotImplementedError( "Should have implemented this" )

Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring.

And the difference between abstract and interface is a hairsplitting thing when you have duck typing.

Java uses interfaces because it doesn't have multiple inheritance.

Because Python has multiple inheritance, you may also see something like this

class SomeAbstraction( object ):
    pass # lots of stuff - but missing something

class Mixin1( object ):
    def something( self ):
        pass # one implementation

class Mixin2( object ):
    def something( self ):
        pass # another

class Concrete1( SomeAbstraction, Mixin1 ):
    pass

class Concrete2( SomeAbstraction, Mixin2 ):
    pass

This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.

what is the difference between json and xml

XML uses a tag structures for presenting items, like <tag>item</tag>, so an XML document is a set of tags nested into each other. And JSON syntax looks like a construction from Javascript language, with all stuff like lists and dictionaries:

{
 'attrib' : 'value',
 'array' : [1, 2, 3]
}

So if you use JSON it's really simple to use a JSON strings in many script languages, especially Javascript and Python.

What's a decent SFTP command-line client for windows?

This little application does the job for me. I could not find another CLI based client that would access my IIS based TLS/SSL secured ftp site: http://netwinsite.com/surgeftp/sslftp.htm

Find if a textbox is disabled or not using jquery

You can use $(":disabled") to select all disabled items in the current context.

To determine whether a single item is disabled you can use $("#textbox1").is(":disabled").

How to create a WPF Window without a border that can be resized via a grip only?

If you set the AllowsTransparency property on the Window (even without setting any transparency values) the border disappears and you can only resize via the grip.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="640" Height="480" 
    WindowStyle="None"
    AllowsTransparency="True"
    ResizeMode="CanResizeWithGrip">

    <!-- Content -->

</Window>

Result looks like:

ClassNotFoundException: org.slf4j.LoggerFactory

It needs "slf4j-simple-1.7.2.jar" to resolve the problem.

I downloaded a zip file "slf4j-1.7.2.zip" from http://slf4j.org/download.html. I extracted the zip file and i got slf4j-simple-1.7.2.jar

Pretty printing XML with javascript

If you are looking for a JavaScript solution just take the code from the Pretty Diff tool at http://prettydiff.com/?m=beautify

You can also send files to the tool using the s parameter, such as: http://prettydiff.com/?m=beautify&s=https://stackoverflow.com/

What is the difference between range and xrange functions in Python 2.X?

It is for optimization reasons.

range() will create a list of values from start to end (0 .. 20 in your example). This will become an expensive operation on very large ranges.

xrange() on the other hand is much more optimised. it will only compute the next value when needed (via an xrange sequence object) and does not create a list of all values like range() does.

How to clear a notification in Android

Please try methods provided in NotificationManagerCompat.

To remove all notifications,

NotificationManagerCompat.from(context).cancelAll();

To remove a particular notification,

NotificationManagerCompat.from(context).cancel(notificationId);

To compare two elements(string type) in XSLT?

First of all, the provided long code:

    <xsl:choose>
        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="OU_NAME"/>
            <fo:block/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:otherwise>
    </xsl:choose>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
        </xsl:if>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:

OU_NAME='OU_ADDR1'

evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

Java, How to add library files in netbeans?

For Netbeans 2020 September version. JDK 11

(Suggesting this for Gradle project only)

1. create libs folder in src/main/java folder of the project

2. copy past all library jars in there

3. open build.gradle in files tab of project window in project's root

4. correct main class (mine is mainClassName = 'uz.ManipulatorIkrom')

5. and in dependencies add next string:

apply plugin: 'java' 
apply plugin: 'jacoco' 
apply plugin: 'application'
description = 'testing netbeans'
mainClassName = 'uz.ManipulatorIkrom' //4th step
repositories {
    jcenter()
}
dependencies {
    implementation fileTree(dir: 'src/main/java/libs', include: '*.jar') //5th step   
}

6. save, clean-build and then run the app

deleting folder from java

If you use Apache Commons IO it's a one-liner:

FileUtils.deleteDirectory(dir);

See FileUtils.deleteDirectory()


Guava used to support similar functionality:

Files.deleteRecursively(dir);

This has been removed from Guava several releases ago.


While the above version is very simple, it is also pretty dangerous, as it makes a lot of assumptions without telling you. So while it may be safe in most cases, I prefer the "official way" to do it (since Java 7):

public static void deleteFileOrFolder(final Path path) throws IOException {
  Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
      throws IOException {
      Files.delete(file);
      return CONTINUE;
    }

    @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) {
      return handleException(e);
    }

    private FileVisitResult handleException(final IOException e) {
      e.printStackTrace(); // replace with more robust error handling
      return TERMINATE;
    }

    @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException e)
      throws IOException {
      if(e!=null)return handleException(e);
      Files.delete(dir);
      return CONTINUE;
    }
  });
};

Android Camera : data intent returns null

Kotlin code that works for me:

 private fun takePhotoFromCamera() {
          val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA)
      }

And get Result :

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
 if (requestCode == PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA) {
         if (resultCode == Activity.RESULT_OK) {
           val photo: Bitmap? =  MediaStore.Images.Media.getBitmap(this.contentResolver, Uri.parse( data!!.dataString)   )
            // Do something here : set image to an ImageView or save it ..   
              imgV_pic.imageBitmap = photo 
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "Camera  , RESULT_CANCELED ")
        }

    }

}

and don't forget to declare request code:

companion object {
 const val PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA = 300
  }

Easiest way to convert month name to month number in JS ? (Jan = 01)

If you are using moment.js:

moment().month("Jan").format("M");

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

In my case I wasn't aware that the PHP run by Apache was different from the one run by CLI. That might be the case if during configuration in httpd.conf you specified a PHP module, not being the default one your CLI uses.

Remove property for all objects in array

A solution using prototypes is only possible when your objects are alike:

function Cons(g) { this.good = g; }
Cons.prototype.bad = "something common";
var array = [new Cons("something 1"), new Cons("something 2"), …];

But then it's simple (and O(1)):

delete Cons.prototype.bad;

How to get the second column from command output?

#!/usr/bin/python
import sys 

col = int(sys.argv[1]) - 1

for line in sys.stdin:
    columns = line.split()

    try:
        print(columns[col])
    except IndexError:
        # ignore
        pass

Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-

ls -lh | co 5

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

Since the reduce method has been removed from the built in function from Python3, don't forget to import the functools in your code. Please look at the code snippet below.

import functools
my_list = [10,15,20,25,35]
sum_numbers = functools.reduce(lambda x ,y : x+y , my_list)
print(sum_numbers)

How to add external library in IntelliJ IDEA?

Intellij IDEA 15: File->Project Structure...->Project Settings->Libraries

SyntaxError: cannot assign to operator

In case it helps someone, if your variables have hyphens in them, you may see this error since hyphens are not allowed in variable names in Python and are used as subtraction operators.

Example:

my-variable = 5   # would result in 'SyntaxError: can't assign to operator'

Using reCAPTCHA on localhost

If you have old key, you should recreate your API Key. Also be aware of proxies.

How to access route, post, get etc. parameters in Zend Framework 2

All the above methods will work fine if your content-type is "application/-www-form-urlencoded". But if your content-type is "application/json" then you will have to do the following:

$params = json_decode(file_get_contents('php://input'), true); print_r($params);

Reason : See #7 in https://www.toptal.com/php/10-most-common-mistakes-php-programmers-make

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

Nothing like these two lines appears in Mike Williams' tutorial:

    wait = true;
    setTimeout("wait = true", 2000);

Here's a Version 3 port:

http://acleach.me.uk/gmaps/v3/plotaddresses.htm

The relevant bit of code is

  // ====== Geocoding ======
  function getAddress(search, next) {
    geo.geocode({address:search}, function (results,status)
      { 
        // If that was successful
        if (status == google.maps.GeocoderStatus.OK) {
          // Lets assume that the first marker is the one we want
          var p = results[0].geometry.location;
          var lat=p.lat();
          var lng=p.lng();
          // Output the data
            var msg = 'address="' + search + '" lat=' +lat+ ' lng=' +lng+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          // Create a marker
          createMarker(search,lat,lng);
        }
        // ====== Decode the error status ======
        else {
          // === if we were sending the requests to fast, try this one again and increase the delay
          if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            nextAddress--;
            delay++;
          } else {
            var reason="Code "+status;
            var msg = 'address="' + search + '" error=' +reason+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          }   
        }
        next();
      }
    );
  }

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

Majorly there are 3 ways of creating Objects-

Simplest one is using object literals.

const myObject = {}

Though this method is the simplest but has a disadvantage i.e if your object has behaviour(functions in it),then in future if you want to make any changes to it you would have to change it in all the objects.

So in that case it is better to use Factory or Constructor Functions.(anyone that you like)

Factory Functions are those functions that return an object.e.g-

function factoryFunc(exampleValue){
   return{
      exampleProperty: exampleValue 
   }
}

Constructor Functions are those functions that assign properties to objects using "this" keyword.e.g-

function constructorFunc(exampleValue){
   this.exampleProperty= exampleValue;
}
const myObj= new constructorFunc(1);

SQL Server IN vs. EXISTS Performance

The execution plans are typically going to be identical in these cases, but until you see how the optimizer factors in all the other aspects of indexes etc., you really will never know.

How to get jSON response into variable from a jquery script

Here's the script, rewritten to use the suggestions above and a change to your no-cache method.

<?php
// Simpler way of making sure all no-cache headers get sent
// and understood by all browsers, including IE.
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));

header('Content-type: application/json');

// set to return response=error
$arr = array ('response'=>'error','comment'=>'test comment here');
echo json_encode($arr);
?>

//the script above returns this:
{"response":"error","comment":"test comment here"}

<script type="text/javascript">
$.ajax({
    type: "POST",
    url: "process.php",
    data: dataString,
    dataType: "json",
    success: function (data) {
        if (data.response == 'captcha') {
            alert('captcha');
        } else if (data.response == 'success') {
            alert('success');
        } else {
            alert('sorry there was an error');
        }
    }

}); // Semi-colons after all declarations, IE is picky on these things.
</script>

The main issue here was that you had a typo in the JSON you were returning ("resonse" instead of "response". This meant that you were looking for the wrong property in the JavaScript code. One way of catching these problems in the future is to console.log the value of data and make sure the property you are looking for is there.

Learning how to use the Chrome debugger tools (or similar tools in Firefox/Safari/Opera/etc.) will also be invaluable.

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

Compare integer in bash, unary operator expected

I need to add my 5 cents. I see everybody use [ or [[, but it worth to mention that they are not part of if syntax.

For arithmetic comparisons, use ((...)) instead.

((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.

See: ArithmeticExpression

How to access the correct `this` inside a callback?

The question revolves around how this keyword behaves in javascript. this behaves differently as below,

  1. The value of this is usually determined by a function execution context.
  2. In the global scope, this refers to the global object (the window object).
  3. If strict mode is enabled for any function then the value of this will be undefined as in strict mode, global object refers to undefined in place of the window object.
  4. The object that is standing before the dot is what this keyword will be bound to.
  5. We can set the value of this explicitly with call(), bind(), and apply()
  6. When the new keyword is used (a constructor), this is bound to the new object being created.
  7. Arrow Functions don’t bind this — instead, this is bound lexically (i.e. based on the original context)

As most of the answers suggest, we can use Arrow function or bind() Method or Self var. I would quote a point about lambdas (Arrow function) from Google JavaScript Style Guide

Prefer using arrow functions over f.bind(this), and especially over goog.bind(f, this). Avoid writing const self = this. Arrow functions are particularly useful for callbacks, which sometimes pass unexpectedly additional arguments.

Google clearly recommends using lambdas rather than bind or const self = this

So the best solution would be to use lambdas as below,

function MyConstructor(data, transport) {
  this.data = data;
  transport.on('data', () => {
    alert(this.data);
  });
}

References:

  1. https://medium.com/tech-tajawal/javascript-this-4-rules-7354abdb274c
  2. arrow-functions-vs-bind

Split comma-separated input box values into array in jquery, and loop through it

var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

Convert object array to hash map, indexed by an attribute value of the Object

A small improvement on the reduce usage:

var arr = [
    { key: 'foo', val: 'bar' },
    { key: 'hello', val: 'world' }
];

var result = arr.reduce((map, obj) => ({
    ...map,
    [obj.key] = obj.val
}), {});

console.log(result);
// { foo: 'bar', hello: 'world' }

Autocompletion of @author in Intellij

You can work around that via a Live Template. Go to Settings -> Live Template, click the "Add"-Button (green plus on the right).

In the "Abbreviation" field, enter the string that should activate the template (e.g. @a), and in the "Template Text" area enter the string to complete (e.g. @author - My Name). Set the "Applicable context" to Java (Comments only maybe) and set a key to complete (on the right).

I tested it and it works fine, however IntelliJ seems to prefer the inbuild templates, so "@a + Tab" only completes "author". Setting the completion key to Space worked however.

To change the user name that is automatically inserted via the File Templates (when creating a class for example), can be changed by adding

-Duser.name=Your name

to the idea.exe.vmoptions or idea64.exe.vmoptions (depending on your version) in the IntelliJ/bin directory.

enter image description here

Restart IntelliJ

What are the differences between Pandas and NumPy+SciPy in Python?

Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.

How to convert an integer to a string in any base?

Here is an example of how to convert a number of any base to another base.

from collections import namedtuple

Test = namedtuple("Test", ["n", "from_base", "to_base", "expected"])


def convert(n: int, from_base: int, to_base: int) -> int:
    digits = []
    while n:
        (n, r) = divmod(n, to_base)
        digits.append(r)    
    return sum(from_base ** i * v for i, v in enumerate(digits))


if __name__ == "__main__":
    tests = [
        Test(32, 16, 10, 50),
        Test(32, 20, 10, 62),
        Test(1010, 2, 10, 10),
        Test(8, 10, 8, 10),
        Test(150, 100, 1000, 150),
        Test(1500, 100, 10, 1050000),
    ]

    for test in tests:
        result = convert(*test[:-1])
        assert result == test.expected, f"{test=}, {result=}"
    print("PASSED!!!")

Find and Replace Inside a Text File from a Bash Command

I was surprised when I stumbled over this...

There is a replace command which ships with the "mysql-server" package, so if you have installed it try it out:

# replace string abc to XYZ in files
replace "abc" "XYZ" -- file.txt file2.txt file3.txt

# or pipe an echo to replace
echo "abcdef" |replace "abc" "XYZ"

See man replace for more on this.

A full list of all the new/popular databases and their uses?

I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.

Get age from Birthdate

JsFiddle

You can calculate with Dates.

var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25

Serializing list to JSON

If using Python 2.5, you may need to import simplejson:

try:
    import json
except ImportError:
    import simplejson as json

Gson: Directly convert String to JsonObject (no POJO)

//import com.google.gson.JsonObject;  
JsonObject complaint = new JsonObject();
complaint.addProperty("key", "value");

Java int to String - Integer.toString(i) vs new Integer(i).toString()

In terms of performance measurement, if you are considering the time performance then the Integer.toString(i); is expensive if you are calling less than 100 million times. Else if it is more than 100 million calls then the new Integer(10).toString() will perform better.

Below is the code through u can try to measure the performance,

public static void main(String args[]) {
            int MAX_ITERATION = 10000000;
        long starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s = Integer.toString(10);
        }
        long endtime = System.currentTimeMillis();
        System.out.println("diff1: " + (endtime-starttime));

        starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s1 = new Integer(10).toString();
        }
        endtime = System.currentTimeMillis();
        System.out.println("diff2: " + (endtime-starttime));
    }

In terms of memory, the

new Integer(i).toString();

will take more memory as it will create the object each time, so memory fragmentation will happen.

How to import Google Web Font in CSS file?

Download the font ttf/other format files, then simply add this CSS code example:

_x000D_
_x000D_
@font-face { font-family: roboto-regular; _x000D_
    src: url('../font/Roboto-Regular.ttf'); } _x000D_
h2{_x000D_
 font-family: roboto-regular;_x000D_
}
_x000D_
_x000D_
_x000D_

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

Android Spinner : Avoid onItemSelected calls during initialization

This worked for me

Spinner's initialization in Android is problematic sometimes the above problem was solved by this pattern.

Spinner.setAdapter();
Spinner.setSelected(false);  // must
Spinner.setSelection(0,true);  //must
Spinner.setonItemSelectedListener(this);

Setting adapter should be first part and onItemSelectedListener(this) will be last when initializing a spinner. By the pattern above my OnItemSelected() is not called during initialization of spinner

Text Editor which shows \r\n?

Sublime Text 3 has a plugin called RawLineEdit that will display line endings and allow the insertion of arbitrary line-ending type:

https://github.com/facelessuser/RawLineEdit

Rounding integer division (instead of truncating)

TLDR: Here's a macro; use it!

// To do (numer/denom), rounded to the nearest whole integer, use:
#define ROUND_DIVIDE(numer, denom) (((numer) + (denom) / 2) / (denom))

Usage example:

int num = ROUND_DIVIDE(13,7); // 13/7 = 1.857 --> rounds to 2, so num is 2

Full answer:

Some of these answers are crazy looking! Codeface nailed it though! (See @0xC0DEFACE's answer here). I really like the type-free macro or gcc statement expression form over the function form, however, so, I wrote this answer with a detailed explanation of what I'm doing (ie: why this mathematically works) and put it into 2 forms:

1. Macro form, with detailed commentary to explain the whole thing:

/// @brief      ROUND_DIVIDE(numerator/denominator): round to the nearest whole integer when doing 
///             *integer* division only
/// @details    This works on *integers only* since it assumes integer truncation will take place automatically
///             during the division! 
/// @notes      The concept is this: add 1/2 to any number to get it to round to the nearest whole integer
///             after integer trunction.
///             Examples:  2.74 + 0.5 = 3.24 --> 3 when truncated
///                        2.99 + 0.5 = 3.49 --> 3 when truncated
///                        2.50 + 0.5 = 3.00 --> 3 when truncated
///                        2.49 + 0.5 = 2.99 --> 2 when truncated
///                        2.00 + 0.5 = 2.50 --> 2 when truncated
///                        1.75 + 0.5 = 2.25 --> 2 when truncated
///             To add 1/2 in integer terms, you must do it *before* the division. This is achieved by 
///             adding 1/2*denominator, which is (denominator/2), to the numerator before the division.
///             ie: `rounded_division = (numer + denom/2)/denom`.
///             ==Proof==: 1/2 is the same as (denom/2)/denom. Therefore, (numer/denom) + 1/2 becomes 
///             (numer/denom) + (denom/2)/denom. They have a common denominator, so combine terms and you get:
///             (numer + denom/2)/denom, which is the answer above.
/// @param[in]  numerator   any integer type numerator; ex: uint8_t, uint16_t, uint32_t, int8_t, int16_t, int32_t, etc
/// @param[in]  denominator any integer type denominator; ex: uint8_t, uint16_t, uint32_t, int8_t, int16_t, int32_t, etc
/// @return     The result of the (numerator/denominator) division rounded to the nearest *whole integer*!
#define ROUND_DIVIDE(numerator, denominator) (((numerator) + (denominator) / 2) / (denominator))

2. GCC Statement Expression form:

See a little more on gcc statement expressions here.

/// @brief      *gcc statement expression* form of the above macro
#define ROUND_DIVIDE2(numerator, denominator)               \
({                                                          \
    __typeof__ (numerator) numerator_ = (numerator);        \
    __typeof__ (denominator) denominator_ = (denominator);  \
    numerator_ + (denominator_ / 2) / denominator_;         \
})

3. C++ Function Template form:

(Added Mar./Apr. 2020)

#include <limits>

// Template form for C++ (with type checking to ensure only integer types are passed in!)
template <typename T>
T round_division(T numerator, T denominator)
{
    // Ensure only integer types are passed in, as this round division technique does NOT work on
    // floating point types since it assumes integer truncation will take place automatically
    // during the division!
    // - The following static assert allows all integer types, including their various `const`,
    //   `volatile`, and `const volatile` variations, but prohibits any floating point type
    //   such as `float`, `double`, and `long double`. 
    // - Reference page: https://en.cppreference.com/w/cpp/types/numeric_limits/is_integer
    static_assert(std::numeric_limits<T>::is_integer, "Only integer types are allowed"); 
    return (numerator + denominator/2)/denominator;
}

Run & test some of this code here:

  1. OnlineGDB: integer rounding during division

Related Answers:

  1. Fixed Point Arithmetic in C Programming - in this answer I go over how to do integer rounding to the nearest whole integer, then tenth place (1 decimal digit to the right of the decimal), hundredth place (2 dec digits), thousandth place (3 dec digits), etc. Search the answer for the section in my code comments called BASE 2 CONCEPT: for more details!
  2. A related answer of mine on gcc's statement expressions: MIN and MAX in C
  3. The function form of this with fixed types: Rounding integer division (instead of truncating)
  4. What is the behavior of integer division?
  5. For rounding up instead of to nearest integer, follow this similar pattern: Rounding integer division (instead of truncating)

References:

  1. https://www.tutorialspoint.com/cplusplus/cpp_templates.htm

todo: test this for negative inputs & update this answer if it works:

#define ROUND_DIVIDE(numer, denom) ((numer < 0) != (denom < 0) ? ((numer) - (denom) / 2) / (denom) : ((numer) + (denom) / 2) / (denom))

Why doesn't Git ignore my specified file?

Please use this command

git rm -rf --cached .
git add .

Sometimes .gitignore files don't work even though they're correct. The reason Git ignores files is that they are not added to the repository. If you added a file that you want to ignore before, it will be tracked by Git, and any skipping matching rules will be skipped. Git does this because the file is already part of the repository.

How can I ignore a property when serializing using the DataContractSerializer?

In XML Serializing, you can use the [XmlIgnore] attribute (System.Xml.Serialization.XmlIgnoreAttribute) to ignore a property when serializing a class.

This may be of use to you (Or it just may be of use to anyone who found this question when attempting to find out how to ignore a property when Serializing in XML, as I was).

How are cookies passed in the HTTP protocol?

The server sends the following in its response header to set a cookie field.

Set-Cookie:name=value

If there is a cookie set, then the browser sends the following in its request header.

Cookie:name=value

See the HTTP Cookie article at Wikipedia for more information.

Regex: Specify "space or start of string" and "space or end of string"

You can use any of the following:

\b      #A word break and will work for both spaces and end of lines.
(^|\s)  #the | means or. () is a capturing group. 


/\b(stackoverflow)\b/

Also, if you don't want to include the space in your match, you can use lookbehind/aheads.

(?<=\s|^)         #to look behind the match
(stackoverflow)   #the string you want. () optional
(?=\s|$)          #to look ahead.

hide div tag on mobile view only?

i just switched positions and worked for me (showing only mobile )

_x000D_
_x000D_
<style>_x000D_
 .MobileContent {_x000D_
_x000D_
     display: none;_x000D_
  text-align:center;_x000D_
_x000D_
 }_x000D_
_x000D_
@media screen and (max-width: 768px) {_x000D_
_x000D_
 .MobileContent {_x000D_
_x000D_
     display:block;_x000D_
_x000D_
 }_x000D_
_x000D_
}_x000D_
</style>_x000D_
<div class="MobileContent"> Something </div>
_x000D_
_x000D_
_x000D_

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

Make sure that your password doesn't have special characters and just keep a plain password (for ex: 12345), it will work. This is the strangest thing that I have ever seen. I spent about 2 hours to figure this out.

Note: 12345 mentioned below is your plain password

GRANT ALL PRIVILEGES ON dbname.* TO 'yourusername'@'%' IDENTIFIED BY '12345';

How to create a private class method?

ExiRe wrote:

Such behavior of ruby is really frustrating. I mean if you move to private section self.method then it is NOT private. But if you move it to class << self then it suddenly works. It is just disgusting.

Confusing it probably is, frustrating it may well be, but disgusting it is definitely not.

It makes perfect sense once you understand Ruby's object model and the corresponding method lookup flow, especially when taking into consideration that private is NOT an access/visibility modifier, but actually a method call (with the class as its recipient) as discussed here... there's no such thing as "a private section" in Ruby.

To define private instance methods, you call private on the instance's class to set the default visibility for subsequently defined methods to private... and hence it makes perfect sense to define private class methods by calling private on the class's class, ie. its metaclass.

Other mainstream, self-proclaimed OO languages may give you a less confusing syntax, but you definitely trade that off against a confusing and less consistent (inconsistent?) object model without the power of Ruby's metaprogramming facilities.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Really the format can be quite simple - sometimes there's no need to predefine a temp table - it will be created from results of the select.

Select FieldA...FieldN 
into #MyTempTable 
from MyTable

So unless you want different types or are very strict on definition, keep things simple. Note also that any temporary table created inside a stored procedure is automatically dropped when the stored procedure finishes executing. If stored procedure A creates a temp table and calls stored procedure B, then B will be able to use the temporary table that A created.

However, it's generally considered good coding practice to explicitly drop every temporary table you create anyway.

How can I run a PHP script in the background after a form is submitted?

If you're on Windows, research proc_open or popen...

But if we're on the same server "Linux" running cpanel then this is the right approach:

#!/usr/bin/php 
<?php
$pid = shell_exec("nohup nice php -f            
'path/to/your/script.php' /dev/null 2>&1 & echo $!");
While(exec("ps $pid"))
{ //you can also have a streamer here like fprintf,        
 // or fgets
}
?>

Don't use fork() or curl if you doubt you can handle them, it's just like abusing your server

Lastly, on the script.php file which is called above, take note of this make sure you wrote:

<?php
ignore_user_abort(TRUE);
set_time_limit(0);
ob_start();
// <-- really optional but this is pure php

//Code to be tested on background

ob_flush(); flush(); 
//this two do the output process if you need some.        
//then to make all the logic possible


str_repeat(" ",1500); 
//.for progress bars or loading images

sleep(2); //standard limit

?>

Is there a pretty print for PHP?

Here's another simple dump without all the overhead of print_r:

function pretty($arr, $level=0){
    $tabs = "";
    for($i=0;$i<$level; $i++){
        $tabs .= "    ";
    }
    foreach($arr as $key=>$val){
        if( is_array($val) ) {
            print ($tabs . $key . " : " . "\n");
            pretty($val, $level + 1);
        } else {
            if($val && $val !== 0){
                print ($tabs . $key . " : " . $val . "\n"); 
            }
        }
    }
}
// Example:
$item["A"] = array("a", "b", "c");
$item["B"] = array("a", "b", "c");
$item["C"] = array("a", "b", "c");

pretty($item);

// -------------
// yields
// -------------
// A : 
//     0 : a
//     1 : b
//     2 : c
// B : 
//     0 : a
//     1 : b
//     2 : c
// C : 
//     0 : a
//     1 : b
//     2 : c

Text not wrapping inside a div element

you can add this line: word-break:break-all; to your CSS-code

GitHub: How to make a fork of public repository private?

You have to duplicate the repo

You can see this doc (from github)

To create a duplicate of a repository without forking, you need to run a special clone command against the original repository and mirror-push to the new one.

In the following cases, the repository you're trying to push to--like exampleuser/new-repository or exampleuser/mirrored--should already exist on GitHub. See "Creating a new repository" for more information.

Mirroring a repository

To make an exact duplicate, you need to perform both a bare-clone and a mirror-push.

Open up the command line, and type these commands:

$ git clone --bare https://github.com/exampleuser/old-repository.git
# Make a bare clone of the repository

$ cd old-repository.git
$ git push --mirror https://github.com/exampleuser/new-repository.git
# Mirror-push to the new repository

$ cd ..
$ rm -rf old-repository.git
# Remove our temporary local repository

If you want to mirror a repository in another location, including getting updates from the original, you can clone a mirror and periodically push the changes.

$ git clone --mirror https://github.com/exampleuser/repository-to-mirror.git
# Make a bare mirrored clone of the repository

$ cd repository-to-mirror.git
$ git remote set-url --push origin https://github.com/exampleuser/mirrored
# Set the push location to your mirror

As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references will be overwritten each time you fetch, so it will always be the same as the original repository. Setting the URL for pushes simplifies pushing to your mirror. To update your mirror, fetch updates and push, which could be automated by running a cron job.

$ git fetch -p origin
$ git push --mirror

https://help.github.com/articles/duplicating-a-repository

Can I Set "android:layout_below" at Runtime Programmatically?

Alternatively you can use the views current layout parameters and modify them:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.below_id);

MySQL - how to front pad zip code with "0"?

you should use UNSIGNED ZEROFILL in your table structure.

How can I make a "color map" plot in matlab?

By default mesh will color surface values based on the (default) jet colormap (i.e. hot is higher). You can additionally use surf for filled surface patches and set the 'EdgeColor' property to 'None' (so the patch edges are non-visible).

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;

% surface in 3D
figure;
surf(Z,'EdgeColor','None');

enter image description here

2D map: You can get a 2D map by switching the view property of the figure

% 2D map using view
figure;
surf(Z,'EdgeColor','None');
view(2);    

enter image description here

... or treating the values in Z as a matrix, viewing it as a scaled image using imagesc and selecting an appropriate colormap.

% using imagesc to view just Z
figure;
imagesc(Z); 
colormap jet; 

enter image description here

The color pallet of the map is controlled by colormap(map), where map can be custom or any of the built-in colormaps provided by MATLAB:

enter image description here

Update/Refining the map: Several design options on the map (resolution, smoothing, axis etc.) can be controlled by the regular MATLAB options. As @Floris points out, here is a smoothed, equal-axis, no-axis labels maps, adapted to this example:

figure;
surf(X, Y, Z,'EdgeColor', 'None', 'facecolor', 'interp');
view(2);
axis equal; 
axis off;

enter image description here

Finding blocking/locking queries in MS SQL (mssql)

You may find this query useful:

SELECT * 
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName' 
AND blocking_session_id <> 0

How can I install a package with go get?

Command go

Download and install packages and dependencies

Usage:

go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.

The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.

The -t flag instructs get to also download the packages required to build the tests for the specified packages.

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

The -v flag enables verbose progress and debug output.

Get also accepts build flags to control the installation. See 'go help build'.

When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.

When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.

Get never checks out or updates code stored in vendor directories.

For more about specifying packages, see 'go help packages'.

For more about how 'go get' finds source code to download, see 'go help importpath'.

This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.

See also: go build, go install, go clean.


For example, showing verbose output,

$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$ 

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

How to parse JSON in Scala using standard Scala classes?

val jsonString =
  """
    |{
    | "languages": [{
    |     "name": "English",
    |     "is_active": true,
    |     "completeness": 2.5
    | }, {
    |     "name": "Latin",
    |     "is_active": false,
    |     "completeness": 0.9
    | }]
    |}
  """.stripMargin

val result = JSON.parseFull(jsonString).map {
  case json: Map[String, List[Map[String, Any]]] =>
    json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get

println(result)

assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

CSS, Images, JS not loading in IIS

For Images use

@Url.Content("~/assets/bg4.jpg")

on a Style use this

style="background-image:url(@Url.Content("~/assets/bg4.jpg"))