Programs & Examples On #Sigabrt

SIGABRT is a Unix signal sent when a program abnormally stops, often leading to a crash.

Xcode error - Thread 1: signal SIGABRT

SIGABRT means in general that there is an uncaught exception. There should be more information on the console.

When does a process get SIGABRT (signal 6)?

abort() sends the calling process the SIGABRT signal, this is how abort() basically works.

abort() is usually called by library functions which detect an internal error or some seriously broken constraint. For example malloc() will call abort() if its internal structures are damaged by a heap overflow.

How do you Sort a DataTable given column and direction?

If you've only got one DataView, you can sort using that instead:

table.DefaultView.Sort = "columnName asc";

Haven't tried it, but I guess you can do this with any number of DataViews, as long as you reference the right one.

eclipse won't start - no java virtual machine was found

Yeah it happend to me right now. Go to Oracle site, and search for Java SDK. Make sure you use the same architeture (x86, x64) of Eclipse.

MD5 hashing in Android

this is working perfectly for me, I used this to get MD5 on LIST Array(then convert it to JSON object), but if you only need to apply it on your data. type format, replace JsonObject with yours.

Especially if you have a mismatch with python MD5 implementation use this!

private static String md5(List<AccelerationSensor> sensor) {

    Gson gson= new Gson();
    byte[] JsonObject = new byte[0];
    try {
        JsonObject = gson.toJson(sensor).getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    MessageDigest m = null;

    try {
        m = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    byte[] thedigest = m.digest(JsonObject);
    String hash = String.format("%032x", new BigInteger(1, thedigest));
    return hash;


}

PHP Fatal error: Call to undefined function json_decode()

The module was install but symbolic link was not in /etc/php5/cli/conf.d

Convert .class to .java

I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."

INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there

Angular ng-class if else

Both John Conde's and ryeballar's answers are correct and will work.

If you want to get too geeky:

  • John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center and it has to decide whether to add/remove left), when clearly only one is needed.

  • Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)


So, you can do the following as an alternative:

ng-class="{true:'center',false:'left'}[page.isSelected(1)]"

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

I had to close and re-open my windows console (or open a new console), and then open the SDK manager (ran android), after which a bunch of updates and installs had to complete.

Java function for arrays like PHP's join()?

Nothing built-in that I know of.

Apache Commons Lang has a class called StringUtils which contains many join functions.

Setting query string using Fetch GET request

Maybe this is better:

const withQuery = require('with-query');

fetch(withQuery('https://api.github.com/search/repositories', {
  q: 'query',
  sort: 'stars',
  order: 'asc',
}))
.then(res => res.json())
.then((json) => {
  console.info(json);
})
.catch((err) => {
  console.error(err);
});

Loop and get key/value pair for JSON array using jQuery

The following should work for a JSON returned string. It will also work for an associative array of data.

for (var key in data)
     alert(key + ' is ' + data[key]);

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Align items in a stack panel?

For those who stumble upon this question, here's how to achieve this layout with a Grid:

<Grid>
    <TextBlock Text="Server:"/>
    <TextBlock Text="http://127.0.0.1" HorizontalAlignment="Right"/>
</Grid>

creates

Server:                                                                   http://127.0.0.1

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

Including this answer because this was the top result for "invalid column name sql" on google and I didn't see this answer here. In my case, I was getting Invalid Column Name, Id1 because I had used the wrong id in my .HasForeignKey statement in my Entity Framework C# code. Once I changed it to match the .HasOne() object's id, the error was gone.

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Why doesn't list have safe "get" method like dictionary?

Credits to jose.angel.jimenez and Gus Bus.


For the "oneliner" fans…


If you want the first element of a list or if you want a default value if the list is empty try:

liste = ['a', 'b', 'c']
value = (liste[0:1] or ('default',))[0]
print(value)

returns a

and

liste = []
value = (liste[0:1] or ('default',))[0]
print(value)

returns default


Examples for other elements…

liste = ['a', 'b', 'c']
print(liste[0:1])  # returns ['a']
print(liste[1:2])  # returns ['b']
print(liste[2:3])  # returns ['c']
print(liste[3:4])  # returns []

With default fallback…

liste = ['a', 'b', 'c']
print((liste[0:1] or ('default',))[0])  # returns a
print((liste[1:2] or ('default',))[0])  # returns b
print((liste[2:3] or ('default',))[0])  # returns c
print((liste[3:4] or ('default',))[0])  # returns default

Possibly shorter:

liste = ['a', 'b', 'c']
value, = liste[:1] or ('default',)
print(value)  # returns a

It looks like you need the comma before the equal sign, the equal sign and the latter parenthesis.


More general:

liste = ['a', 'b', 'c']
f = lambda l, x, d: l[x:x+1] and l[x] or d
print(f(liste, 0, 'default'))  # returns a
print(f(liste, 1, 'default'))  # returns b
print(f(liste, 2, 'default'))  # returns c
print(f(liste, 3, 'default'))  # returns default

Tested with Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)

store return json value in input hidden field

just set the hidden field with javascript :

document.getElementById('elementId').value = 'whatever';

or do I miss something?

How do I concatenate multiple C++ strings on one line?

If you are willing to use c++11 you can utilize user-defined string literals and define two function templates that overload the plus operator for a std::string object and any other object. The only pitfall is not to overload the plus operators of std::string, otherwise the compiler doesn't know which operator to use. You can do this by using the template std::enable_if from type_traits. After that strings behave just like in Java or C#. See my example implementation for details.

Main code

#include <iostream>
#include "c_sharp_strings.hpp"

using namespace std;

int main()
{
    int i = 0;
    float f = 0.4;
    double d = 1.3e-2;
    string s;
    s += "Hello world, "_ + "nice to see you. "_ + i
            + " "_ + 47 + " "_ + f + ',' + d;
    cout << s << endl;
    return 0;
}

File c_sharp_strings.hpp

Include this header file in all all places where you want to have these strings.

#ifndef C_SHARP_STRING_H_INCLUDED
#define C_SHARP_STRING_H_INCLUDED

#include <type_traits>
#include <string>

inline std::string operator "" _(const char a[], long unsigned int i)
{
    return std::string(a);
}

template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
                        !std::is_same<char, T>::value &&
                        !std::is_same<const char*, T>::value, std::string>::type
operator+ (std::string s, T i)
{
    return s + std::to_string(i);
}

template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
                        !std::is_same<char, T>::value &&
                        !std::is_same<const char*, T>::value, std::string>::type
operator+ (T i, std::string s)
{
    return std::to_string(i) + s;
}

#endif // C_SHARP_STRING_H_INCLUDED

git - Your branch is ahead of 'origin/master' by 1 commit

git reset HEAD <file1> <file2> ...

remove the specified files from the next commit

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

You can try using jquery.pep.js:

jquery.pep.js is a lightweight jQuery plugin which turns any DOM element into a draggable object. It works across mostly all browsers, from old to new, from touch to click. I built it to serve a need in which jQuery UI’s draggable was not fulfilling, since it didn’t work on touch devices (without some hackery).

Website, GitHub link

Getting char from string at specified index

Getting one char from string at specified index

Dim pos As Integer
Dim outStr As String
pos = 2 
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)

outStr="b"

How to create a sticky footer that plays well with Bootstrap 3

   <style type="text/css">

     /* Sticky footer styles
     -------------------------------------------------- */

     html,
     body {
       height: 100%;
       /* The html and body elements cannot have any padding or margin. */
     }

     /* Wrapper for page content to push down footer */
     #wrap {
       min-height: 100%;
       height: auto !important;
       height: 100%;
       /* Negative indent footer by it's height */
       margin: 0 auto -60px;
     }

     /* Set the fixed height of the footer here */
     #push,
     #footer {
       height: 60px;
     }
     #footer {
       background-color: #f5f5f5;
     }

     /* Lastly, apply responsive CSS fixes as necessary */
     @media (max-width: 767px) {
       #footer {
         margin-left: -20px;
         margin-right: -20px;
         padding-left: 20px;
         padding-right: 20px;
       }
     }



     /* Custom page CSS
     -------------------------------------------------- */
     /* Not required for template or sticky footer method. */

     .container {
       width: auto;
       max-width: 680px;
     }
     .container .credit {
       margin: 20px 0;
     }

   </style>


<div id="wrap">

  <!-- Begin page content -->
  <div class="container">
    <div class="page-header">
      <h1>Sticky footer</h1>
    </div>
    <p class="lead">Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS.</p>
    <p>Use <a href="./sticky-footer-navbar.html">the sticky footer</a> with a fixed navbar if need be, too.</p>
  </div>

  <div id="push"></div>
</div>

<div id="footer">
  <div class="container">
    <p class="muted credit">Example courtesy <a href="http://martinbean.co.uk">Martin Bean</a> and <a href="http://ryanfait.com/sticky-footer/">Ryan Fait</a>.</p>
  </div>
</div>

Should we pass a shared_ptr by reference or by value?

Here's Herb Sutter's take

Guideline: Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership.

Guideline: Express that a function will store and share ownership of a heap object using a by-value shared_ptr parameter.

Guideline: Use a non-const shared_ptr& parameter only to modify the shared_ptr. Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).

What is the easiest way to install BLAS and LAPACK for scipy?

For completeness, though this probably would not work well given your particular setup (external program + Windows), one can also acquire Scipy hassle-free as part of the (large) SageMath download.

Error message "Forbidden You don't have permission to access / on this server"

I had the same issue for a specific controller only - which was really weird. I had a folder in the root of the CI folder that had the same name as the controller I was trying to access... Because of that, CI was directing the request to this directory instead of the controller itself.

After removing this folder (which was there a bit by mistake), it all worked fine.

To be more clear, here is what it looked like:

/ci/controller/register.php

/ci/register/

I had to remove /ci/register/.

How to clear https proxy setting of NPM?

npm config rm proxy
npm config rm https-proxy
unset HTTP_PROXY
unset HTTPS_PROXY
unset http_proxy
unset https_proxy

Damn finally this does the trick in Debian Jessie with privoxy (ad remover) installed, Thank you :-)

How to change CSS using jQuery?

wrong code:$("#myParagraph").css({"backgroundColor":"black","color":"white");

its missing "}" after white"

change it to this

 $("#myParagraph").css({"background-color":"black","color":"white"});

How can I listen for keypress event on the whole page?

I think this does the best job

https://angular.io/api/platform-browser/EventManager

for instance in app.component

constructor(private eventManager: EventManager) {
    const removeGlobalEventListener = this.eventManager.addGlobalEventListener(
      'document',
      'keypress',
      (ev) => {
        console.log('ev', ev);
      }
    );
  }

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

I am not sure I understand what you want, but based on what I understood

the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"

you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)

p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")

worked for me, see the picture

enter image description here

I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code

ImportError: No module named 'selenium'

It's 2020 now, use python3 consistently

  • pip3 install selenium
  • python3 xxx.py

I meet the same problem when I install selenium using pip3, but run scripts using python.

How to disable compiler optimizations in gcc?

You can disable optimizations if you pass -O0 with the gcc command-line.

E.g. to turn a .C file into a .S file call:

gcc -O0 -S test.c

How do I properly force a Git push?

I had the same question but figured it out finally. What you most likely need to do is run the following two git commands (replacing hash with the git commit revision number):

git checkout <hash>
git push -f HEAD:master

Getting multiple keys of specified value of a generic Dictionary?

Can't you create a subclass of Dictionary which has that functionality?


    public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
    {
        private Dictionary < TValue, TKey > _keys;

        public TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set 
            { 
                base[key] = value;
                _keys[value] = key;
            }
        }

        public MyDict()
        {
            _keys = new Dictionary < TValue, TKey >();
        }

        public TKey GetKeyFromValue(TValue value)
        {
            return _keys[value];
        }
    }

EDIT: Sorry, didn't get code right first time.

How do I escape double quotes in attributes in an XML String in T-SQL?

tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:

declare @xml xml 
set @xml = "<transaction><item value=""hi"" /></transaction>"

If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:

declare @xml xml
set @xml = "<transaction><item value=""hi &quot;mom&quot; lol"" /></transaction>"

UTF-8 byte[] to String

Java String class has a built-in-constructor for converting byte array to string.

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

String value = new String(byteArray, "UTF-8");

Convert/cast an stdClass object to another class

BTW: Converting is highly important if you are serialized, mainly because the de-serialization breaks the type of objects and turns into stdclass, including DateTime objects.

I updated the example of @Jadrovski, now it allows objects and arrays.

example

$stdobj=new StdClass();
$stdobj->field=20;
$obj=new SomeClass();
fixCast($obj,$stdobj);

example array

$stdobjArr=array(new StdClass(),new StdClass());
$obj=array(); 
$obj[0]=new SomeClass(); // at least the first object should indicates the right class.
fixCast($obj,$stdobj);

code: (its recursive). However, i don't know if its recursive with arrays. May be its missing an extra is_array

public static function fixCast(&$destination,$source)
{
    if (is_array($source)) {
        $getClass=get_class($destination[0]);
        $array=array();
        foreach($source as $sourceItem) {
            $obj = new $getClass();
            fixCast($obj,$sourceItem);
            $array[]=$obj;
        }
        $destination=$array;
    } else {
        $sourceReflection = new \ReflectionObject($source);
        $sourceProperties = $sourceReflection->getProperties();
        foreach ($sourceProperties as $sourceProperty) {
            $name = $sourceProperty->getName();
            if (is_object(@$destination->{$name})) {
                fixCast($destination->{$name}, $source->$name);
            } else {
                $destination->{$name} = $source->$name;
            }
        }
    }
}

Transform char array into String

I have search it again and search this question in baidu. Then I find 2 ways:

1,

_x000D_
_x000D_
char ch[]={'a','b','c','d','e','f','g','\0'};_x000D_
string s=ch;_x000D_
cout<<s;
_x000D_
_x000D_
_x000D_

Be aware to that '\0' is necessary for char array ch.

2,

_x000D_
_x000D_
#include<iostream>_x000D_
#include<string>_x000D_
#include<strstream>_x000D_
using namespace std;_x000D_
_x000D_
int main()_x000D_
{_x000D_
 char ch[]={'a','b','g','e','d','\0'};_x000D_
 strstream s;_x000D_
 s<<ch;_x000D_
 string str1;_x000D_
 s>>str1;_x000D_
 cout<<str1<<endl;_x000D_
 return 0;_x000D_
}
_x000D_
_x000D_
_x000D_

In this way, you also need to add the '\0' at the end of char array.

Also, strstream.h file will be abandoned and be replaced by stringstream

Prevent any form of page refresh using jQuery/Javascript

Although its not a good idea to disable F5 key you can do it in JQuery as below.

<script type="text/javascript">
function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };

$(document).ready(function(){
     $(document).on("keydown", disableF5);
});
</script>

Hope this will help!

Install pdo for postgres Ubuntu

If you are using PHP 5.6, the command is:

sudo apt-get install php5.6-pgsql

Difference between final and effectively final

'Effectively final' is a variable which would not give compiler error if it were to be appended by 'final'

From a article by 'Brian Goetz',

Informally, a local variable is effectively final if its initial value is never changed -- in other words, declaring it final would not cause a compilation failure.

lambda-state-final- Brian Goetz

How do you join on the same table, twice, in mysql?

Given the following tables..

Domain Table
dom_id | dom_url

Review Table
rev_id | rev_dom_from | rev_dom_for

Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.

Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for

If you are still stuck, please be more specific with exactly it is that you don't understand.

Can I have onScrollListener for a ScrollView?

Here's a derived HorizontalScrollView I wrote to handle notifications about scrolling and scroll ending. It properly handles when a user has stopped actively scrolling and when it fully decelerates after a user lets go:

public class ObservableHorizontalScrollView extends HorizontalScrollView {
    public interface OnScrollListener {
        public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY);
        public void onEndScroll(ObservableHorizontalScrollView scrollView);
    }

    private boolean mIsScrolling;
    private boolean mIsTouching;
    private Runnable mScrollingRunnable;
    private OnScrollListener mOnScrollListener;

    public ObservableHorizontalScrollView(Context context) {
        this(context, null, 0);
    }

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();

        if (action == MotionEvent.ACTION_MOVE) {
            mIsTouching = true;
            mIsScrolling = true;
        } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            if (mIsTouching && !mIsScrolling) {
                if (mOnScrollListener != null) {
                    mOnScrollListener.onEndScroll(this);
                }
            }

            mIsTouching = false;
        }

        return super.onTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);

        if (Math.abs(oldX - x) > 0) {
            if (mScrollingRunnable != null) {
                removeCallbacks(mScrollingRunnable);
            }

            mScrollingRunnable = new Runnable() {
                public void run() {
                    if (mIsScrolling && !mIsTouching) {
                        if (mOnScrollListener != null) {
                            mOnScrollListener.onEndScroll(ObservableHorizontalScrollView.this);
                        }
                    }

                    mIsScrolling = false;
                    mScrollingRunnable = null;
                }
            };

            postDelayed(mScrollingRunnable, 200);
        }

        if (mOnScrollListener != null) {
            mOnScrollListener.onScrollChanged(this, x, y, oldX, oldY);
        }
    }

    public OnScrollListener getOnScrollListener() {
        return mOnScrollListener;
    }

    public void setOnScrollListener(OnScrollListener mOnEndScrollListener) {
        this.mOnScrollListener = mOnEndScrollListener;
    }

}

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

My problem was solved by creating a Windows user without an accent or special characters and reinstalling android studio on that user. Another change is to change the environment variables:

Left Click in My Computer > Advanced System Settings> Advanced > Environment Variables

ANDROID_HOME = c:\my_sdk_path

ANDROID_SDK_ROOT = c:\my_sdk_path

JAVA_HOME = c:\program files\Java\yourJavaPath

  • the default path of SDK is c:\users\youruser\AppData\LocalAndroid\sdk

Environment variables

Add in Path Variable the values:

  1. %ANDROID_HOME%\platform-tools

  2. %ANDROID_HOME%\tools

path variables

path values

After changes, restart windows and try again!

How to convert JSON to a Ruby hash

You can use the nice_hash gem: https://github.com/MarioRuiz/nice_hash

require 'nice_hash'
my_string = '{"val":"test","val1":"test1","val2":"test2"}'

# on my_hash will have the json as a hash, even when nested with arrays
my_hash = my_string.json

# you can filter and get what you want even when nested with arrays
vals = my_string.json(:val1, :val2)

# even you can access the keys like this:
puts my_hash._val1
puts my_hash.val1
puts my_hash[:val1]

How can I remove time from date with Moment.js?

With newer versions of moment.js you can also do this:

var dateTime = moment();

var dateValue = moment({
    year: dateTime.year(),
    month: dateTime.month(),
    day: dateTime.date()
});

See: http://momentjs.com/docs/#/parsing/object/.

What is bootstrapping?

Boot strapping the dictionary meaning is to start up with minimum resources. In the Context of an OS the OS should be able to swiftly load once the Power On Self Test (POST) determines that its safe to wake up the CPU. The boot strap code will be run from the BIOS. BIOS is a small sized ROM. Generally it is a jump instruction to the set of instructions which will load the Operating system to the RAM. The destination of the Jump is the Boot sector in the Hard Disk. Once the bios program checks it is a valid Boot sector which contains the starting address of the stored OS, ie whether it is a valid MBR (Master Boot Record) or not. If its a valid MBR the OS will be copied to the memory (RAM)from there on the OS takes care of Memory and Process management.

Javascript - check array for value

If you don't care about legacy browsers:

if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )

if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:

if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )

Resizing image in Java

We're doing this to create thumbnails of images:

  BufferedImage tThumbImage = new BufferedImage( tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB );
  Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
  tGraphics2D.setBackground( Color.WHITE );
  tGraphics2D.setPaint( Color.WHITE );
  tGraphics2D.fillRect( 0, 0, tThumbWidth, tThumbHeight );
  tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );
  tGraphics2D.drawImage( tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null ); //draw the image scaled

  ImageIO.write( tThumbImage, "JPG", tThumbnailTarget ); //write the image to a file

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

The bitmap constructor has resizing built in.

Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");

http://msdn.microsoft.com/en-us/library/0wh0045z.aspx

If you want control over interpolation modes see this post.

MySQL CREATE FUNCTION Syntax

MySQL create function syntax:

DELIMITER //

CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
    RETURNS CHAR(250)
    BEGIN
        DECLARE fullname CHAR(250);
        SET fullname=CONCAT(fname,' ',lname);
        RETURN fullname;
    END //

DELIMITER ;

Use This Function In Your Query

SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a


SELECT GETFULLNAME("Biswarup","Adhikari") as myname;

Watch this Video how to create mysql function and how to use in your query

Create Mysql Function Video Tutorial

Python: Best way to add to sys.path relative to the current running script

Create a wrapper module project/bin/lib, which contains this:

import sys, os

sys.path.insert(0, os.path.join(
    os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib'))

import mylib

del sys.path[0], sys, os

Then you can replace all the cruft at the top of your scripts with:

#!/usr/bin/python
from lib import mylib

Convert Mat to Array/Vector in OpenCV

Here is another possible solution assuming matrix have one column( you can reshape original Mat to one column Mat via reshape):

Mat matrix= Mat::zeros(20, 1, CV_32FC1);
vector<float> vec;
matrix.col(0).copyTo(vec);

what's the correct way to send a file from REST web service to client?

I don't recommend encoding binary data in base64 and wrapping it in JSON. It will just needlessly increase the size of the response and slow things down.

Simply serve your file data using GET and application/octect-streamusing one of the factory methods of javax.ws.rs.core.Response (part of the JAX-RS API, so you're not locked into Jersey):

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
  File file = ... // Initialize this to the File path you want to serve.
  return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
      .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
      .build();
}

If you don't have an actual File object, but an InputStream, Response.ok(entity, mediaType) should be able to handle that as well.

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

Why can't I use Docker CMD multiple times to run multiple services?

To address why CMD is designed to run only one service per container, let's just realize what would happen if the secondary servers run in the same container are not trivial / auxiliary but "major" (e.g. storage bundled with the frontend app). For starters, it would break down several important containerization features such as horizontal (auto-)scaling and rescheduling between nodes, both of which assume there is only one application (source of CPU load) per container. Then there is the issue of vulnerabilities - more servers exposed in a container means more frequent patching of CVEs...

So let's admit that it is a 'nudge' from Docker (and Kubernetes/Openshift) designers towards good practices and we should not reinvent workarounds (SSH is not necessary - we have docker exec / kubectl exec / oc rsh designed to replace it).

  • More info

https://devops.stackexchange.com/questions/447/why-it-is-recommended-to-run-only-one-process-in-a-container

Round double in two decimal places in C#?

This works:

inputValue = Math.Round(inputValue, 2);

Difference between $.ajax() and $.get() and $.load()

The methods provide different layers of abstraction.

  • $.ajax() gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.

  • $.get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler.

  • $(selector).load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).

It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax().

E.g. you won't use $.load(), if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax() or $.get().

How can I add JAR files to the web-inf/lib folder in Eclipse?

Add the jar file to your WEB-INF/lib folder. Right-click your project in Eclipse, and go to "Build Path > Configure Build Path" Add the "Web App Libraries" library This will ensure all WEB-INF/lib jars are included on the classpath. helped me..

Drag and drop in WEB-INF/lib folder and restart eclipse ans start webservice then create client

How can I find the first occurrence of a sub-string in a python string?

to implement this in algorithmic way, by not using any python inbuilt function . This can be implemented as

def find_pos(string,word):

    for i in range(len(string) - len(word)+1):
        if string[i:i+len(word)] == word:
            return i
    return 'Not Found'

string = "the dude is a cool dude"
word = 'dude1'
print(find_pos(string,word))
# output 4

Flutter - The method was called on null

The reason for this error occurs is that you are using the CryptoListPresenter _presenter without initializing.

I found that CryptoListPresenter _presenter would have to be initialized to fix because _presenter.loadCurrencies() is passing through a null variable at the time of instantiation;

there are two ways to initialize

  1. Can be initialized during an declaration, like this

    CryptoListPresenter _presenter = CryptoListPresenter();
    
  2. In the second, initializing(with assigning some value) it when initState is called, which the framework will call this method once for each state object.

    @override
    void initState() {
      _presenter = CryptoListPresenter(...);
    }
    

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

String Padding in C

Oh okay, makes sense. So I did this:

    char foo[10] = "hello";
    char padded[16];
    strcpy(padded, foo);
    printf("%s", StringPadRight(padded, 15, " "));

Thanks!

Python: Find in list

Finding the first occurrence

There's a recipe for that in itertools:

def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

For example, the following code finds the first odd number in a list:

>>> first_true([2,3,4,5], None, lambda x: x%2==1)
3  

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Just perform the following steps:

1a) Connect to mysql (via localhost)

mysql -uroot -p

1b) If the mysql server is running in Kubernetes (K8s) and being accessed via a NodePort

kubectl exec -it [pod-name] -- /bin/bash
mysql -uroot -p
  1. Create user

    CREATE USER 'user'@'%' IDENTIFIED BY 'password';

  2. Grant permissions

    GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' WITH GRANT OPTION;

  3. Flush privileges

    FLUSH PRIVILEGES;

How to pass prepareForSegue: an object

I have a sender class, like this

@class MyEntry;

@interface MySenderEntry : NSObject
@property (strong, nonatomic) MyEntry *entry;
@end

@implementation MySenderEntry
@end

I use this sender class for passing objects to prepareForSeque:sender:

-(void)didSelectItemAtIndexPath:(NSIndexPath*)indexPath
{
    MySenderEntry *sender = [MySenderEntry new];
    sender.entry = [_entries objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:SEGUE_IDENTIFIER_SHOW_ENTRY sender:sender];
}

-(void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_SHOW_ENTRY]) {
        NSAssert([sender isKindOfClass:[MySenderEntry class]], @"MySenderEntry");
        MySenderEntry *senderEntry = (MySenderEntry*)sender;
        MyEntry *entry = senderEntry.entry;
        NSParameterAssert(entry);

        [segue destinationViewController].delegate = self;
        [segue destinationViewController].entry = entry;
        return;
    }

    if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_HISTORY]) {
        // ...
        return;
    }

    if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_FAVORITE]) {
        // ...
        return;
    }
}

Convert a number into a Roman Numeral in javaScript

Here is my "as functional as it gets" solution.

_x000D_
_x000D_
var numerals = ["I","V","X","L","C","D","M"],_x000D_
      number = 1453,_x000D_
      digits = Array(~~(Math.log10(number)+1)).fill(number).map((n,i) => Math.trunc(n%Math.pow(10,i+1)/Math.pow(10,i))),  // <- [3,5,4,1]_x000D_
      result = digits.reduce((p,c,i) => (c === 0 ? ""_x000D_
                                                 : c < 4 ? numerals[2*i].repeat(c)_x000D_
                                                         : c === 4 ? numerals[2*i] + numerals[2*i+1]_x000D_
                                                                   : c < 9 ? numerals[2*i+1] + numerals[2*i].repeat(c-5)_x000D_
                                                                           : numerals[2*i] + numerals[2*i+2]) + p,"");_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Sort a list of tuples by 2nd item (integer value)

For an in-place sort, use

foo = [(list of tuples)]
foo.sort(key=lambda x:x[0]) #To sort by first element of the tuple

How can I make XSLT work in chrome?

What Eric says is correct.

In the xsl, for the xsl:stylesheet tag have the following attributes

version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"

It works fine in chrome.

Install pip in docker

An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine. They offer pip out of the box (and have a smaller footprint which leads to faster builds etc).

Compare two files report difference in python

The difflib library is useful for this, and comes in the standard library. I like the unified diff format.

http://docs.python.org/2/library/difflib.html#difflib.unified_diff

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
        )
        for line in diff:
            sys.stdout.write(line)

Outputs:

--- hosts0
+++ hosts1
@@ -1,5 +1,4 @@
 one
 two
-dogs
 three

And here is a dodgy version that ignores certain lines. There might be edge cases that don't work, and there are surely better ways to do this, but maybe it will be good enough for your purposes.

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
            n=0,
        )
        for line in diff:
            for prefix in ('---', '+++', '@@'):
                if line.startswith(prefix):
                    break
            else:
                sys.stdout.write(line[1:])

JavaScript: How do I print a message to the error console?

As always, Internet Explorer is the big elephant in rollerskates that stops you just simply using console.log().

jQuery's log can be adapted quite easily, but is a pain having to add it everywhere. One solution if you're using jQuery is to put it into your jQuery file at the end, minified first:

function log()
{
    if (arguments.length > 0)
    {
        // Join for graceful degregation
        var args = (arguments.length > 1) ? Array.prototype.join.call(arguments, " ") : arguments[0];

        // This is the standard; Firebug and newer WebKit browsers support this.
        try {
            console.log(args);
            return true;
        } catch(e) {
            // Newer Opera browsers support posting erros to their consoles.
            try {
                opera.postError(args);
                return true;
            } 
            catch(e) 
            {
            }
        }

        // Catch all; a good old alert box.
        alert(args);
        return false;
    }
}

javascript: optional first argument in function

You can pass all your optional arguments in an object as the first argument. The second argument is your callback. Now you can accept as many arguments as you want in your first argument object, and make it optional like so:

function my_func(op, cb) {
    var options = (typeof arguments[0] !== "function")? arguments[0] : {},
        callback = (typeof arguments[0] !== "function")? arguments[1] : arguments[0];

    console.log(options);
    console.log(callback);
}

If you call it without passing the options argument, it will default to an empty object:

my_func(function () {});
=> options: {}
=> callback: function() {}

If you call it with the options argument you get all your params:

my_func({param1: 'param1', param2: 'param2'}, function () {});
=> options: {param1: "param1", param2: "param2"}
=> callback: function() {}

This could obviously be tweaked to work with more arguments than two, but it get's more confusing. If you can just use an object as your first argument then you can pass an unlimited amount of arguments using that object. If you absolutely need more optional arguments (e.g. my_func(arg1, arg2, arg3, ..., arg10, fn)), then I would suggest using a library like ArgueJS. I have not personally used it, but it looks promising.

Only local connections are allowed Chrome and Selenium webdriver

C#:

    ChromeOptions options = new ChromeOptions();

    options.AddArgument("C:/Users/username/Documents/Visual Studio 2012/Projects/Interaris.Test/Interaris.Tes/bin/Debug/chromedriver.exe");

    ChromeDriver chrome = new ChromeDriver(options);

Worked for me.

How can I include null values in a MIN or MAX?

It's a bit ugly but because the NULLs have a special meaning to you, this is the cleanest way I can think to do it:

SELECT recordid, MIN(startdate),
   CASE WHEN MAX(CASE WHEN enddate IS NULL THEN 1 ELSE 0 END) = 0
        THEN MAX(enddate)
   END
FROM tmp GROUP BY recordid

That is, if any row has a NULL, we want to force that to be the answer. Only if no rows contain a NULL should we return the MIN (or MAX).

Can someone explain how to append an element to an array in C programming?

Short answer is: You don't have any choice other than:

arr[4] = 5;

Using the RUN instruction in a Dockerfile with 'source' does not work

Building on the answers on this page I would add that you have to be aware that each RUN statement runs independently of the others with /bin/sh -c and therefore won't get any environment vars that would normally be sourced in login shells.

The best way I have found so far is to add the script to /etc/bash.bashrc and then invoke each command as bash login.

RUN echo "source /usr/local/bin/virtualenvwrapper.sh" >> /etc/bash.bashrc
RUN /bin/bash --login -c "your command"

You could for instance install and setup virtualenvwrapper, create the virtual env, have it activate when you use a bash login, and then install your python modules into this env:

RUN pip install virtualenv virtualenvwrapper
RUN mkdir -p /opt/virtualenvs
ENV WORKON_HOME /opt/virtualenvs
RUN echo "source /usr/local/bin/virtualenvwrapper.sh" >> /etc/bash.bashrc
RUN /bin/bash --login -c "mkvirtualenv myapp"
RUN echo "workon mpyapp" >> /etc/bash.bashrc
RUN /bin/bash --login -c "pip install ..."

Reading the manual on bash startup files helps understand what is sourced when.

Xcode 4: How do you view the console?

If you just want to have the log output display when you run your app then you can go into XCode4 preferences -> Alerts and click on 'Run starts' on the left hand column.

Then select 'Show Debugger' and when you run the app the NSLog output will be displayed below the editor pane.

This way you don't have to select on the 'up arrow' button at the bottom bar.

Hide text within HTML?

This will keep its space, but not show anything;

opacity: 0.0;

This will hide the object fully, plus its (reserved) space;

display: none;

html button to send email

You can use an anchor to attempt to open the user's default mail client, prepopulated, with mailto:, but you cannot send the actual email. *Apparently it is possible to do this with a form action as well, but browser support is varied and unreliable, so I do not suggest it.

HTML cannot send mail, you need to use a server side language like php, which is another topic. There are plently of good resources on how to do this here on SO or elsewhere on the internet.

If you are using php, I see SwiftMailer suggested quite a bit.

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

In my case, the "Default Web Site" in IIS didn't have a binding for localhost on port 80. You should have a binding for whatever your value in the .csproj file is.

Why does PEP-8 specify a maximum line length of 79 characters?

I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.

Find ALL tweets from a user (not just the first 3,200)

http://greptweet.com/ is an attempt to surpass the 3200 limit by backing up tweets, and besides that is useful for simple searches.

Use a LIKE statement on SQL Server XML Datatype

Another option is to search the XML as a string by converting it to a string and then using LIKE. However as a computed column can't be part of a WHERE clause you need to wrap it in another SELECT like this:

SELECT * FROM
    (SELECT *, CONVERT(varchar(MAX), [COLUMNA]) as [XMLDataString] FROM TABLE) x
WHERE [XMLDataString] like '%Test%'

Is <div style="width: ;height: ;background: "> CSS?

1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.

How to use setInterval and clearInterval?

clearInterval is one option:

var interval = setInterval(doStuff, 2000); // 2000 ms = start after 2sec 
function doStuff() {
  alert('this is a 2 second warning');
  clearInterval(interval);
}

Javascript - How to extract filename from a file input control

//x=address or src
if(x.includes('/')==true){xp=x.split('/')} //split address
if(x.includes('\\')==true){xp=x.split('\\')} //split address
xl=xp.length*1-1;xn=xp[xl] //file==xn
xo=xn.split('.'); //file parts=xo
if(xo.lenght>2){xol=xo.length-1;xt=xo[xol];xr=xo.splice(xol,1);
xr=xr.join('.'); // multiple . in name
}else{
xr=xo[0]; //filename=xr
xt=xo[1]; //file ext=xt
}
xp.splice(xl,1); //remove file
xf=xp.join('/'); //folder=xf , also corrects slashes

//result
alert("filepath: "+x+"\n folder: "+xf+"("+xl+")\n file: "+xn+"\n filename: "+xr+"\n .ext:  "+xt)

How to extract file name from path?

I can't believe how overcomplicated some of these answers are... (no offence!)

Here's a single-line function that will get the job done:


**Extract Filename from <code>x:\path\filename</code>:**

Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"\")+1):End Function

**Extract Path from <code>x:\path\filename</code>:**

Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"\")):End Function

Examples:

examples

Joining two table entities in Spring Data JPA

This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

    @Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

How to get number of rows using SqlDataReader in C#

You can't get a count of rows directly from a data reader because it's what is known as a firehose cursor - which means that the data is read on a row by row basis based on the read being performed. I'd advise against doing 2 reads on the data because there's the potential that the data has changed between doing the 2 reads, and thus you'd get different results.

What you could do is read the data into a temporary structure, and use that in place of the second read. Alternatively, you'll need to change the mechanism by which you retrieve the data and use something like a DataTable instead.

Windows equivalent of linux cksum command

Here is a C# implementation of the *nix cksum command line utility for windows https://cksum.codeplex.com/

Different CURRENT_TIMESTAMP and SYSDATE in oracle

  1. SYSDATE, systimestamp return datetime of server where database is installed. SYSDATE - returns only date, i.e., "yyyy-mm-dd". systimestamp returns date with time and zone, i.e., "yyyy-mm-dd hh:mm:ss:ms timezone"
  2. now() returns datetime at the time statement execution, i.e., "yyyy-mm-dd hh:mm:ss"
  3. CURRENT_DATE - "yyyy-mm-dd", CURRENT_TIME - "hh:mm:ss", CURRENT_TIMESTAMP - "yyyy-mm-dd hh:mm:ss timezone". These are related to a record insertion time.

How do I convert a datetime to date?

Use the date() method:

datetime.datetime.now().date()

Ping with timestamp on Windows CLI

Try this:

Create a batch file with the following:

echo off

cd\

:start

echo %time% >> c:\somedirectory\pinghostname.txt

ping pinghostname >> c:\somedirectory\pinghostname.txt

goto start

You can add your own options to the ping command based on your requirements. This doesn't put the time stamp on the same line as the ping, but it still gets you the info you need.

An even better way is to use fping, go here http://www.kwakkelflap.com/fping.html to download it.

Laravel - check if Ajax request

$request->wantsJson()

You can try $request->wantsJson() if $request->ajax() does not work

$request->ajax() works if your JavaScript library sets an X-Requested-With HTTP header.

By default Laravel set this header in js/bootstrap.js

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

In my case, I used a different frontend code and I had to put this header manually for $request->ajax() to work.

But $request->wantsJson() will check the axios query without the need for a header X-Requested-With:

// Determine if the current request is asking for JSON. This checks Content-Type equals application/json.
$request->wantsJson()
// or 
\Request::wantsJson() // not \Illuminate\Http\Request

Angular 2: How to call a function after get a response from subscribe http.post

You can do this be using a new Subject too:

Typescript:

let subject = new Subject();

get_categories(...) {
   this.http.post(...).subscribe( 
      (response) => {
         this.total = response.json();
         subject.next();
      }
   ); 

   return subject; // can be subscribed as well 
}

get_categories(...).subscribe(
   (response) => {
     // ...
   }
);

sed whole word search and replace

Use \b for word boundaries:

sed -i 's/\boldtext\b/newtext/g' <file>

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

JavaScript object: access variable property by name as string

Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    function displayFile(whatOption, whatColor) {_x000D_
      var Test01 = {_x000D_
        rectangle: {_x000D_
          red: "RectangleRedFile",_x000D_
          blue: "RectangleBlueFile"_x000D_
        },_x000D_
        square: {_x000D_
          red: "SquareRedFile",_x000D_
          blue: "SquareBlueFile"_x000D_
        }_x000D_
      };_x000D_
      var filename = Test01[whatOption][whatColor];_x000D_
      alert(filename);_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
  <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Bootstrap 4 - Glyphicons migration?

Overview:

I am using bootstrap 4 without glyphicons. I found a problem with bootstrap treeview that depends upon glyphicons. I am using treeview as is, and I am using scss @extend to translate the icon class styles to font awesome class styles. I think this is quite slick (if you ask me)!

Details:

I used scss @extend to handle it for me.

I previously decided to use font-awesome for no better reason than I have used it in the past.

When I went to try bootstrap treeview, I found that the icons were missing, because I didn't have glyphicons installed.

I decided to use the scss @extend feature, to have the glyphicon classes use the font-awesome classes as so:

.treeview {
  .glyphicon {
    @extend .fa;
  }
  .glyphicon-minus {
    @extend .fa-minus;
  }
  .glyphicon-plus {
    @extend .fa-plus;
  }
}

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

Correct; you cannot truncate a table which has an FK constraint on it.

Typically my process for this is:

  1. Drop the constraints
  2. Trunc the table
  3. Recreate the constraints.

(All in a transaction, of course.)

Of course, this only applies if the child has already been truncated. Otherwise I go a different route, dependent entirely on what my data looks like. (Too many variables to get into here.)

The original poster determined WHY this is the case; see this answer for more details.

Select from multiple tables without a join?

You should try this

 SELECT t1.*,t2.* FROM t1,t2

How to not wrap contents of a div?

If you don't care about a minimum width for the div and really just don't want the div to expand across the whole container, you can float it left -- floated divs by default expand to support their contents, like so:

<form>
    <div style="float: left; background-color: blue">
        <input type="button" name="blah" value="lots and lots of characters"/>
        <input type="button" name="blah2" value="some characters"/>
    </div>
</form>

XMLHttpRequest status 0 (responseText is empty)

I had to add my current IP address (again) to the Atlas MongoDB whitelist and so got rid of the XMLHttpRequest status 0 error

disable Bootstrap's Collapse open/close animation

Maybe not a direct answer to the question, but a recent addition to the official documentation describes how jQuery can be used to disable transitions entirely just by:

$.support.transition = false

Setting the .collapsing CSS transitions to none as mentioned in the accepted answer removed the animation. But this — in Firefox and Chromium for me — creates an unwanted visual issue on collapse of the navbar.

For instance, visit the Bootstrap navbar example and add the CSS from the accepted answer:

.collapsing {
     -webkit-transition: none;
     transition: none;
}

What I currently see is when the navbar collapses, the bottom border of the navbar momentarily becomes two pixels instead of one, then disconcertingly jumps back to one. Using jQuery, this artifact doesn't appear.

Search input with an icon Bootstrap 4

Here is an input box with a search icon on the right.

  <div class="input-group">
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
      <div class="input-group-append">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
  </div>

Here is an input box with a search icon on the left.

  <div class="input-group">
      <div class="input-group-prepend">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
  </div>

Prevent PDF file from downloading and printing

Creating a video with QuickTime's screen capture or anything similar kind of defeats all the effort to protect your document file from being copied.

Can linux cat command be used for writing text to file?

Here's another way -

cat > outfile.txt
>Enter text
>to save press ctrl-d

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Here is my solution (Bootstrap 4):

<div class="alert alert-warning row">
    <div class="col">
        Bootstrap breakpoint is
    </div>
    <div class="col">
        <div class="d-block d-sm-none">
            XS
        </div>
        <div class="d-none d-sm-block d-md-none">
            SM
        </div>
        <div class="d-none d-md-block d-lg-none">
            MD
        </div>
        <div class="d-none d-lg-block d-xl-none">
            MD
        </div>
        <div class="d-none d-xl-block">
            MD
        </div>
    </div>
</div>

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

It does nothing because no events have been bound to the event. If I recall correctly, jQuery maintains its own list of event handlers that are bound to NodeLists for performance and other purposes.

MVC - Set selected value of SelectList

A bit late to the party here but here's how simple this is:

ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82");

this uses my method getcountries to populate a model called countries, obviousley you would replace this with whatever your datasource is, a model etc, then sets the id as the value in the selectlist. then just add the last param, in this case "82" to select the default selected item.

[edit] Here's how to use this in Razor:

@Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })

Important: Also, 1 other thing to watch out for, Make sure the model field that you use to store the selected Id (in this case model.CountryId) from the dropdown list is nullable and is set to null on the first page load. This one gets me every time.

Hope this saves someone some time.

Best way to remove an event handler in jQuery?

All the approaches described did not work for me because I was adding the click event with on() to the document where the element was created at run-time:

$(document).on("click", ".button", function() {
    doSomething();
});


My workaround:

As I could not unbind the ".button" class I just assigned another class to the button that had the same CSS styles. By doing so the live/on-event-handler ignored the click finally:

// prevent another click on the button by assigning another class
$(".button").attr("class","buttonOff");

Hope that helps.

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

It is not necessary to stop timer, see nice solution from this post:

"You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately."

private void CreatorLoop(object state) 
 {
   if (Monitor.TryEnter(lockObject))
   {
     try
     {
       // Work here
     }
     finally
     {
       Monitor.Exit(lockObject);
     }
   }
 }

How to Define Callbacks in Android?

No need to define a new interface when you can use an existing one: android.os.Handler.Callback. Pass an object of type Callback, and invoke callback's handleMessage(Message msg).

SQLite DateTime comparison

You could also write up your own user functions to handle dates in the format you choose. SQLite has a fairly simple method for writing your own user functions. For example, I wrote a few to add time durations together.

Change color of Back button in navigation bar

You should add this line

 self.navigationController?.navigationBar.topItem?.backBarButtonItem?.tintColor = .black

How can I add a new column and data to a datatable that already contains data?

Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";

Switching between GCC and Clang/LLVM using CMake

If the default compiler chosen by cmake is gcc and you have installed clang, you can use the easy way to compile your project with clang:

$ mkdir build && cd build
$ CXX=clang++ CC=clang cmake ..
$ make -j2

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

VBA Excel sort range by specific column

If the starting cell of the range and of the key is static, the solution can be very simple:

Range("A3").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Sort key1:=Range("B3", Range("B3").End(xlDown)), _
order1:=xlAscending, Header:=xlNo

How do I access the HTTP request header fields via JavaScript?

This can be accessed through Javascript because it's a property of the loaded document, not of its parent.

Here's a quick example:

<script type="text/javascript">
document.write(document.referrer);
</script>

The same thing in PHP would be:

<?php echo $_SERVER["HTTP_REFERER"]; ?>

How do I delete an exported environment variable?

Walkthrough of creating and deleting an environment variable in bash:

Test if the DUALCASE variable exists:

el@apollo:~$ env | grep DUALCASE
el@apollo:~$ 

It does not, so create the variable and export it:

el@apollo:~$ DUALCASE=1
el@apollo:~$ export DUALCASE

Check if it is there:

el@apollo:~$ env | grep DUALCASE
DUALCASE=1

It is there. So get rid of it:

el@apollo:~$ unset DUALCASE

Check if it's still there:

el@apollo:~$ env | grep DUALCASE
el@apollo:~$ 

The DUALCASE exported environment variable is deleted.

Extra commands to help clear your local and environment variables:

Unset all local variables back to default on login:

el@apollo:~$ CAN="chuck norris"
el@apollo:~$ set | grep CAN
CAN='chuck norris'
el@apollo:~$ env | grep CAN
el@apollo:~$
el@apollo:~$ exec bash
el@apollo:~$ set | grep CAN
el@apollo:~$ env | grep CAN
el@apollo:~$

exec bash command cleared all the local variables but not environment variables.

Unset all environment variables back to default on login:

el@apollo:~$ export DOGE="so wow"
el@apollo:~$ env | grep DOGE
DOGE=so wow
el@apollo:~$ env -i bash
el@apollo:~$ env | grep DOGE
el@apollo:~$

env -i bash command cleared all the environment variables to default on login.

number of values in a list greater than a certain number

I'll add a map and filter version because why not.

sum(map(lambda x:x>5, j))
sum(1 for _ in filter(lambda x:x>5, j))

How to name and retrieve a stash by name in git?

git stash save is deprecated as of 2.15.x/2.16, instead you can use git stash push -m "message"

You can use it like this:

git stash push -m "message"

where "message" is your note for that stash.

In order to retrieve the stash you can use: git stash list. This will output a list like this, for example:

stash@{0}: On develop: perf-spike
stash@{1}: On develop: node v10

Then you simply use apply giving it the stash@{index}:

git stash apply stash@{1}

References git stash man page

How can I split a string into segments of n characters?

Some clean solution without using regular expressions:

/**
* Create array with maximum chunk length = maxPartSize
* It work safe also for shorter strings than part size
**/
function convertStringToArray(str, maxPartSize){

  const chunkArr = [];
  let leftStr = str;
  do {

    chunkArr.push(leftStr.substring(0, maxPartSize));
    leftStr = leftStr.substring(maxPartSize, leftStr.length);

  } while (leftStr.length > 0);

  return chunkArr;
};

Usage example - https://jsfiddle.net/maciejsikora/b6xppj4q/.

I also tried to compare my solution to regexp one which was chosen as right answer. Some test can be found on jsfiddle - https://jsfiddle.net/maciejsikora/2envahrk/. Tests are showing that both methods have similar performance, maybe on first look regexp solution is little bit faster, but judge it Yourself.

Create parameterized VIEW in SQL Server 2008

no. You can use UDF in which you can pass parameters.

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

How do I fix it?

This error means that the JRE that is being used to execute your class code does not recognise the version of Java used. Usually because the version of Java that generated your class file (i.e. compiled it) is newer.

To fix it, you can either

a) Compile your Java sources with the same, or older, version of the Java compiler as will be used to run it. i.e. install the appropriate JDK.

b) Compile your Java sources with the newer version of the Java compiler but in compatibility mode. i.e. use the -target parameter.

c) Run your compiled classes in a JRE that is the same, or newer, version as the JDK used to compile the classes.

You can check the versions you are currently using with javac -version for the compiler, and java -version for the runtime.

Should I install the JDK, and setup my PATH variable to the JDK instead of JRE?

For compilation, certainly, install and configure the specific JDK that you want.

For runtime, you can use the one that comes with the JDK or a standalone JRE, but regardless, make sure that you have installed the right versions and that you have configured your PATH such that there are no surprises.

What is the difference between the PATH variable in JRE or JDK?

The PATH environment variable tells the command shell where to look for the command you type. When you type java, the command shell interpreter will look through all the locations specified in the PATH variable, from left to right, to find the appropriate java runtime executable to run. If you have multiple versions of Java installed - i.e. you have the java executable in multiple locations specified in the PATH variable, then the first one encountered when going from left to right will be the one that is executed.

The compiler command is javac and only comes with the JDK. The runtime command is java and comes with the JDK and is in the JRE.

It is likely that you have one version (51.0 = Java 7) of javac installed, and you also have the same version of java installed, but that another previous version of java is appearing earlier in the PATH and so is being invoked instead of the one you expect.

How to create a Rectangle object in Java using g.fillRect method

Note:drawRect and fillRect are different.

Draws the outline of the specified rectangle:

public void drawRect(int x,
        int y,
        int width,
        int height)

Fills the specified rectangle. The rectangle is filled using the graphics context's current color:

public abstract void fillRect(int x,
        int y,
        int width,
        int height)

PHP Check for NULL

Sometimes, when I know that I am working with numbers, I use this logic (if result is not greater than zero):

if (!$result['column']>0){

}

How to read from stdin with fgets()?

here a concatenation solution:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 10

int main() {
  char *text = calloc(1,1), buffer[BUFFERSIZE];
  printf("Enter a message: \n");
  while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */
  {
    text = realloc( text, strlen(text)+1+strlen(buffer) );
    if( !text ) ... /* error handling */
    strcat( text, buffer ); /* note a '\n' is appended here everytime */
    printf("%s\n", buffer);
  }
  printf("\ntext:\n%s",text);
  return 0;
}

What is the difference between document.location.href and document.location?

typeof document.location; // 'object'
typeof document.location.href; // 'string'

The href property is a string, while document.location itself is an object.

How can I open a popup window with a fixed size using the HREF tag?

You might want to consider using a div element pop-up window that contains an iframe.

jQuery Dialog is a simple way to get started. Just add an iframe as the content.

Easiest way to change font and font size

Maybe something like this:

yourformName.YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

Or if you are in the same class as the form then simply do this:

YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

The constructor takes diffrent parameters (so pick your poison). Like this:

Font(Font, FontStyle)   
Font(FontFamily, Single)
Font(String, Single)
Font(FontFamily, Single, FontStyle)
Font(FontFamily, Single, GraphicsUnit)
Font(String, Single, FontStyle)
Font(String, Single, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit)
Font(String, Single, FontStyle, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte)
Font(String, Single, FontStyle, GraphicsUnit, Byte)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte, Boolean)
Font(String, Single, FontStyle, GraphicsUnit, Byte, Boolean)

Reference here

Add zero-padding to a string

myInt.ToString("D4");

Absolute and Flexbox in React Native

The first step would be to add

position: 'absolute',

then if you want the element full width, add

left: 0,
right: 0,

then, if you want to put the element in the bottom, add

bottom: 0,
// don't need set top: 0

if you want to position the element at the top, replace bottom: 0 by top: 0

Should you always favor xrange() over range()?

I would just like to say that it REALLY isn't that difficult to get an xrange object with slice and indexing functionality. I have written some code that works pretty dang well and is just as fast as xrange for when it counts (iterations).

from __future__ import division

def read_xrange(xrange_object):
    # returns the xrange object's start, stop, and step
    start = xrange_object[0]
    if len(xrange_object) > 1:
       step = xrange_object[1] - xrange_object[0]
    else:
        step = 1
    stop = xrange_object[-1] + step
    return start, stop, step

class Xrange(object):
    ''' creates an xrange-like object that supports slicing and indexing.
    ex: a = Xrange(20)
    a.index(10)
    will work

    Also a[:5]
    will return another Xrange object with the specified attributes

    Also allows for the conversion from an existing xrange object
    '''
    def __init__(self, *inputs):
        # allow inputs of xrange objects
        if len(inputs) == 1:
            test, = inputs
            if type(test) == xrange:
                self.xrange = test
                self.start, self.stop, self.step = read_xrange(test)
                return

        # or create one from start, stop, step
        self.start, self.step = 0, None
        if len(inputs) == 1:
            self.stop, = inputs
        elif len(inputs) == 2:
            self.start, self.stop = inputs
        elif len(inputs) == 3:
            self.start, self.stop, self.step = inputs
        else:
            raise ValueError(inputs)

        self.xrange = xrange(self.start, self.stop, self.step)

    def __iter__(self):
        return iter(self.xrange)

    def __getitem__(self, item):
        if type(item) is int:
            if item < 0:
                item += len(self)

            return self.xrange[item]

        if type(item) is slice:
            # get the indexes, and then convert to the number
            start, stop, step = item.start, item.stop, item.step
            start = start if start != None else 0 # convert start = None to start = 0
            if start < 0:
                start += start
            start = self[start]
            if start < 0: raise IndexError(item)
            step = (self.step if self.step != None else 1) * (step if step != None else 1)
            stop = stop if stop is not None else self.xrange[-1]
            if stop < 0:
                stop += stop

            stop = self[stop]
            stop = stop

            if stop > self.stop:
                raise IndexError
            if start < self.start:
                raise IndexError
            return Xrange(start, stop, step)

    def index(self, value):
        error = ValueError('object.index({0}): {0} not in object'.format(value))
        index = (value - self.start)/self.step
        if index % 1 != 0:
            raise error
        index = int(index)


        try:
            self.xrange[index]
        except (IndexError, TypeError):
            raise error
        return index

    def __len__(self):
        return len(self.xrange)

Honestly, I think the whole issue is kind of silly and xrange should do all of this anyway...

How can I get list of values from dict?

Follow the below example --

songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]

print("====================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')

playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')

# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))

Create a root password for PHPMyAdmin

  • Go tohttp://localhost/security/index.php
  • Select language, it redirects to http://localhost/security/xamppsecurity.php
  • You will find an option to change the password here

Windows Batch Files: if else

you have to do like this...

if not "A%1" == "A"

if the input argument %1 is null, your code will have problem.

Inversion of Control vs Dependency Injection

Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the ones getting the work done.
Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality.

There are several basic techniques to implement inversion of control. These are:

  • Using a factory pattern
  • Using a service locator pattern
  • Using a dependency injection of any given below type:

    1). A constructor injection
    2). A setter injection
    3). An interface injection

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

I did everything and didn't worked. I uninstalled Xcode 10 and installed Xcode 9.4 then it worked out of the box !

Get the filename of a fileupload in a document through JavaScript

Using code like this in a form I can capture the original source upload filename, copy it to a second simple input field. This is so user can provide an alternate upload filename in submit request since the file upload filename is immutable.

    <input type="file" id="imgup1" name="imagefile">
      onchange="document.getElementsByName('imgfn1')[0].value = document.getElementById('imgup1').value;">
    <input type="text" name="imgfn1" value="">

How to trigger ngClick programmatically

The syntax is the following:

function clickOnUpload() {
  $timeout(function() {
    angular.element('#myselector').triggerHandler('click');
  });
};

// Using Angular Extend
angular.extend($scope, {
  clickOnUpload: clickOnUpload
});

// OR Using scope directly
$scope.clickOnUpload = clickOnUpload;

More info on Angular Extend way here.

If you are using old versions of angular, you should use trigger instead of triggerHandler.

If you need to apply stop propagation you can use this method as follows:

<a id="myselector" ng-click="clickOnUpload(); $event.stopPropagation();">
  Something
</a>

jQuery - simple input validation - "empty" and "not empty"

    jQuery("#input").live('change', function() {
        // since we check more than once against the value, place it in a var.
        var inputvalue = $("#input").attr("value");

        // if it's value **IS NOT** ""
        if(inputvalue !== "") {
            jQuery(this).css('outline', 'solid 1px red'); 
        }   

        // else if it's value **IS** ""
        else if(inputvalue === "") {
            alert('empty'); 
        }

    });

Fatal error: unexpectedly found nil while unwrapping an Optional values

Nil Coalescing Operator can be used as well.

rowName = rowName != nil ?rowName!.stringFromCamelCase():""

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

I had the same when following MvcMusicStore Tutorial in Part 4 and replaced the given connection String with this:

add name="MusicStoreEntities" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;database=MvcMusicStore;User ID=sa;password=" providerName="System.Data.SqlClient"/>

It worked for me.

How to install SQL Server Management Studio 2008 component only

I am just updating this with Microsoft SQL Server Management Studio 2008 R2 version. if you run the installer normally, you can just add Management Tools – Basic, and by clicking Basic it should select Management Tools – Complete.

That is what worked for me.

Reading a JSP variable from JavaScript

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In my view page:

<p:dataTable  ...>
<p:column>
<p:commandLink actionListener="#{inquirySOController.viewDetail}" 
               process="@this" update=":mainform:dialog_content"
           oncomplete="dlg2.show()">
    <h:graphicImage library="images" name="view.png"/>
    <f:param name="trxNo" value="#{item.map['trxNo']}"/>
</p:commandLink>
</p:column>
</p:dataTable>

backing bean

 public void viewDetail(ActionEvent e) {

    String trxNo = getFacesContext().getRequestParameterMap().get("trxNo");

    for (DTO item : list) {
        if (item.get("trxNo").toString().equals(trxNo)) {
            System.out.println(trxNo);
            setSelectedItem(item);
            break;
        }
    }
}

How do I copy to the clipboard in JavaScript?

For the security reason you can't do that. You must choose Flash for copying to the clipboard.

I suggest this one: http://zeroclipboard.org/

SQL Server replace, remove all after certain character

For situations when I need to replace or match(find) something against string I prefer using regular expressions.

Since, the regular expressions are not fully supported in T-SQL you can implement them using CLR functions. Furthermore, you do not need any C# or CLR knowledge at all as all you need is already available in the MSDN String Utility Functions Sample.

In your case, the solution using regular expressions is:

SELECT [dbo].[RegexReplace] ([MyColumn], '(;.*)', '')
FROM [dbo].[MyTable]

But implementing such function in your database is going to help you solving more complex issues at all.


The example below shows how to deploy only the [dbo].[RegexReplace] function, but I will recommend to you to deploy the whole String Utility class.

  1. Enabling CLR Integration. Execute the following Transact-SQL commands:

    sp_configure 'clr enabled', 1
    GO
    RECONFIGURE
    GO  
    
  2. Bulding the code (or creating the .dll). Generraly, you can do this using the Visual Studio or .NET Framework command prompt (as it is shown in the article), but I prefer to use visual studio.

    • create new class library project:

      enter image description here

    • copy and paste the following code in the Class1.cs file:

      using System;
      using System.IO;
      using System.Data.SqlTypes;
      using System.Text.RegularExpressions;
      using Microsoft.SqlServer.Server;
      
      public sealed class RegularExpression
      {
          public static string Replace(SqlString sqlInput, SqlString sqlPattern, SqlString sqlReplacement)
          {
              string input = (sqlInput.IsNull) ? string.Empty : sqlInput.Value;
              string pattern = (sqlPattern.IsNull) ? string.Empty : sqlPattern.Value;
              string replacement = (sqlReplacement.IsNull) ? string.Empty : sqlReplacement.Value;
              return Regex.Replace(input, pattern, replacement);
          }
      }
      
    • build the solution and get the path to the created .dll file:

      enter image description here

    • replace the path to the .dll file in the following T-SQL statements and execute them:

      IF OBJECT_ID(N'RegexReplace', N'FS') is not null
      DROP Function RegexReplace;
      GO
      
      IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'StringUtils')
      DROP ASSEMBLY StringUtils;
      GO
      
      DECLARE @SamplePath nvarchar(1024)
      -- You will need to modify the value of the this variable if you have installed the sample someplace other than the default location.
      Set @SamplePath = 'C:\Users\gotqn\Desktop\StringUtils\StringUtils\StringUtils\bin\Debug\'
      CREATE ASSEMBLY [StringUtils] 
      FROM @SamplePath + 'StringUtils.dll'
      WITH permission_set = Safe;
      GO
      
      
      CREATE FUNCTION [RegexReplace] (@input nvarchar(max), @pattern nvarchar(max), @replacement nvarchar(max))
      RETURNS nvarchar(max)
      AS EXTERNAL NAME [StringUtils].[RegularExpression].[Replace]
      GO
      
    • That's it. Test your function:

      declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
      insert into @MyTable ([id], MyText)
      select 1, 'some text; some more text'
      union all select 2, 'text again; even more text'
      union all select 3, 'text without a semicolon'
      union all select 4, null -- test NULLs
      union all select 5, '' -- test empty string
      union all select 6, 'test 3 semicolons; second part; third part'
      union all select 7, ';' -- test semicolon by itself    
      
      SELECT [dbo].[RegexReplace] ([MyText], '(;.*)', '')
      FROM @MyTable
      
      select * from @MyTable
      

How do you use a variable in a regular expression?

For anyone looking to use variable with the match method, this worked for me

var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight

ssl.SSLError: tlsv1 alert protocol version

As of July 2018, Pypi now requires that clients connecting to it use TLS 1.2. This is an issue if you're using the version of python shipped with MacOS (2.7.10) because it only supports TLS 1.0. You can change the version of ssl that python is using to fix the problem or upgrade to a newer version of python. Use homebrew to install the new version of python outside of the default library location.

brew install python@2

Check for special characters in string

You can try this:

regex = [\W_]

It will definitely help you.

How to wait until WebBrowser is completely loaded in VB.NET?

Sometimes if you use JavaScript the DocumentComplete event don't return the right answer; I use the event ProgressChanged instead:

Private Sub WebBrowser1_ProgressChanged(sender As Object, e As WebBrowserProgressChangedEventArgs) Handles WebBrowser1.ProgressChanged

        Console.WriteLine("Current Progress: " + e.CurrentProgress.ToString)

        If e.CurrentProgress = e.MaximumProgress Then

            ' The maximum progress is reached
            load_started = True

        End If

        ' The page is confirmed downloaded after the progress returns to 0
        If e.CurrentProgress = 0 Then

            If load_started Then

                ' The page is ready to print or download...
                WebBrowser1.Print()
                load_started = False

            End If

        End If

End Sub

How can you integrate a custom file browser/uploader with CKEditor?

I spent a while trying to figure this one out and here is what I did. I've broken it down very simply as that is what I needed.

Directly below your ckeditor text area, enter the upload file like this >>>>

<form action="welcomeeditupload.asp" method="post" name="deletechecked">
    <div align="center">
        <br />
        <br />
        <label></label>
        <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"><%=(rslegschedule.Fields.Item("welcomevar").Value)%></textarea>
        <script type="text/javascript">
        //<![CDATA[
            CKEDITOR.replace( 'editor1',
            {
                filebrowserUploadUrl : 'updateimagedone.asp'
            });
        //]]>
        </script>
        <br />
        <br />
        <br />
        <input type="submit" value="Update">
    </div>
</form>

'and then add your upload file, here is mine which is written in ASP. If you're using PHP, etc. simply replace the ASP with your upload script but make sure the page outputs the same thing.

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
    if Request("CKEditorFuncNum")=1 then
        Set Upload = Server.CreateObject("Persits.Upload")
        Upload.OverwriteFiles = False
        Upload.SetMaxSize 5000000, True
        Upload.CodePage = 65001

        On Error Resume Next
        Upload.Save "d:\hosting\belaullach\senate\legislation"

        Dim picture
        For Each File in Upload.Files
            Ext = UCase(Right(File.Path, 3))
            If Ext <> "JPG" Then
                    If Ext <> "BMP" Then
                    Response.Write "File " & File.Path & " is not a .jpg or .bmp file." & "<BR>"
                    Response.write "You can only upload .jpg or .bmp files." & "<BR>" & "<BR>"
                    End if
            Else
                File.SaveAs Server.MapPath(("/senate/legislation") & "/" & File.fileName)
                f1=File.fileName
            End If
        Next
    End if

    fnm="/senate/legislation/"&f1
    imgop = "<html><body><script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction('1','"&fnm&"');</script></body></html>;"
    'imgop="callFunction('1','"&fnm&"',"");"
    Response.write imgop
%>

Bat file to run a .exe at the command prompt

If you want to be real smart, at the command line type:

echo svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service >CreateService.cmd

Then you have CreateService.cmd that you can run whenever you want (.cmd is just another extension for .bat files)

Using C++ filestreams (fstream), how can you determine the size of a file?

Like this:

long begin, end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size: " << (end-begin) << " bytes." << endl;

Resize UIImage and change the size of UIImageView

- (UIImage *)image:(UIImage*)originalImage scaledToSize:(CGSize)size
{
    //avoid redundant drawing
    if (CGSizeEqualToSize(originalImage.size, size))
    {
        return originalImage;
    }

    //create drawing context
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);

    //draw
    [originalImage drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];

    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //return image
    return image;
}

C# Inserting Data from a form into an access Database

Password is a reserved word. Bracket that field name to avoid confusing the db engine.

INSERT into Login (Username, [Password])

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

one liner simple way

_x000D_
_x000D_
var arr = [9,1,2,4,3,4,9]
console.log(arr.filter((ele,indx)=>indx!==arr.indexOf(ele))) //get the duplicates
console.log(arr.filter((ele,indx)=>indx===arr.indexOf(ele))) //remove the duplicates
_x000D_
_x000D_
_x000D_

Iterating over ResultSet and adding its value in an ArrayList

If I've understood your problem correctly, there are two possible problems here:

  • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
  • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

I think that the second point is probably your problem here.

Lets say you only had 1 row returned, as follows:

Col 1, Col 2, Col 3 
A    ,     B,     C

Your code as it stands would only get A - it wouldn't get the rest of the columns.

I suggest you change your code as follows:

ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>(); 
while (resultset.next()) {                      
    int i = 1;
    while(i <= numberOfColumns) {
        arrayList.add(resultset.getString(i++));
    }
    System.out.println(resultset.getString("Col 1"));
    System.out.println(resultset.getString("Col 2"));
    System.out.println(resultset.getString("Col 3"));                    
    System.out.println(resultset.getString("Col n"));
}

Edit:

To get the number of columns:

ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();

What does "request for member '*******' in something not a structure or union" mean?

It may also happen in the following case:

eg. if we consider the push function of a stack:

typedef struct stack
{
    int a[20];
    int head;
}stack;

void push(stack **s)
{
    int data;
    printf("Enter data:");
    scanf("%d",&(*s->a[++*s->head])); /* this is where the error is*/
}

main()
{
    stack *s;
    s=(stack *)calloc(1,sizeof(stack));
    s->head=-1;
    push(&s);
    return 0;
}

The error is in the push function and in the commented line. The pointer s has to be included within the parentheses. The correct code:

scanf("%d",&( (*s)->a[++(*s)->head]));

Export data from Chrome developer tool

In Chrome, in the Developer Tools, under Network, in the Name column, right-click and select "Save as HAR with content". Then open a new tab, go to https://toolbox.googleapps.com/apps/har_analyzer/ and open the saved HAR file.

Globally catch exceptions in a WPF application?

In addition what others mentioned here, note that combining the Application.DispatcherUnhandledException (and its similars) with

<configuration>
  <runtime>  
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
</configuration>

in the app.config will prevent your secondary threads exception from shutting down the application.

How to print to the console in Android Studio?

Run your application in debug mode by clicking on

enter image description here

in the upper menu of Android Studio.

In the bottom status bar, click 5: Debug button, next to the 4: Run button.

Now you should select the Logcat console.

In search box, you can type the tag of your message, and your message should appear, like in the following picture (where the tag is CREATION):

enter image description here

Check this article for more information.

Regular expression for validating names and surnames?

BTW, do you plan to only permit the Latin alphabet, or do you also plan to try to validate Chinese, Arabic, Hindi, etc.?

As others have said, don't even try to do this. Step back and ask yourself what you are actually trying to accomplish. Then try to accomplish it without making any assumptions about what people's names are, or what they mean.

'negative' pattern matching in python

 if not (line.startswith("OK ") or line.strip() == "."):
     print line

How do I get git to default to ssh and not https for new repositories

The response provided by Trevor is correct.

But here is what you can directly add in your .gitconfig:

# Enforce SSH
[url "ssh://[email protected]/"]
  insteadOf = https://github.com/
[url "ssh://[email protected]/"]
  insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
  insteadOf = https://bitbucket.org/

How to compare files from two different branches?

git diff can show you the difference between two commits:

git diff mybranch master -- myfile.cs

Or, equivalently:

git diff mybranch..master -- myfile.cs

Note you must specify the relative path to the file. So if the file were in the src directory, you'd say src/myfile.cs instead of myfile.cs.

Using the latter syntax, if either side is HEAD it may be omitted (e.g. master.. compares master to HEAD).

You may also be interested in mybranch...master (from git diff docs):

This form is to view the changes on the branch containing and up to the second <commit>, starting at a common ancestor of both <commit>. git diff A...B is equivalent to git diff $(git-merge-base A B) B.

In other words, this will give a diff of changes in master since it diverged from mybranch (but without new changes since then in mybranch).


In all cases, the -- separator before the file name indicates the end of command line flags. This is optional unless Git will get confused if the argument refers to a commit or a file, but including it is not a bad habit to get into. See https://stackoverflow.com/a/13321491/54249 for a few examples.


The same arguments can be passed to git difftool if you have one configured.

how to calculate percentage in python

This is because (100/500) is an integer expression yielding 0.

Try

per = 100.0 * tota / 500

there's no need for the float() call, since using a floating-point literal (100.0) will make the entire expression floating-point anyway.

JPanel setBackground(Color.BLACK) does nothing

If your panel is 'not opaque' (transparent) you wont see your background color.

How to set an "Accept:" header on Spring RestTemplate request?

I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders. (You can also specify the HTTP method you want to use.)

For example,

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

HttpEntity<String> entity = new HttpEntity<>("body", headers);

restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

I prefer this solution because it's strongly typed, ie. exchange expects an HttpEntity.

However, you can also pass that HttpEntity as a request argument to postForObject.

HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class); 

This is mentioned in the RestTemplate#postForObject Javadoc.

The request parameter can be a HttpEntity in order to add additional HTTP headers to the request.

How to find my realm file?

I found my realm file by issuing this command in Terminal: sudo find / -name "*.realm".

Hope this helps!

C# testing to see if a string is an integer?

Maybe this can be another solution

try
{
    Console.Write("write your number : ");
    Console.WriteLine("Your number is : " + int.Parse(Console.ReadLine()));
}
catch (Exception x)
{
    Console.WriteLine(x.Message);
}
Console.ReadLine();

Get number days in a specified month using JavaScript?

The following takes any valid datetime value and returns the number of days in the associated month... it eliminates the ambiguity of both other answers...

 // pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
    return new Date(anyDateInMonth.getFullYear(), 
                    anyDateInMonth.getMonth()+1, 
                    0).getDate();}

How can I exit from a javascript function?

if ( condition ) {
    return;
}

The return exits the function returning undefined.

The exit statement doesn't exist in javascript.

The break statement allows you to exit a loop, not a function. For example:

var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}

This also works with the for and the switch loops.

How do I tell Python to convert integers into words

Use pynum2word module that can be found at sourceforge

>>> import num2word
>>> num2word.to_card(15)
'fifteen'
>>> num2word.to_card(55)
'fifty-five'
>>> num2word.to_card(1555)
'one thousand, five hundred and fifty-five'

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

I had the similar issue. It happened every time when I run a pack of database (Spring JDBC) tests with SpringJUnit4ClassRunner, so I resolved the issue putting @DirtiesContext annotation for each test in order to cleanup the application context and release all resources thus each test could run with a new initalization of the application context.

multiple plot in one figure in Python

Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.

In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()

Hiding button using jQuery

It depends on the jQuery selector that you use. Since id should be unique within the DOM, the first one would be simple:

$('#Comanda').hide();

The second one might require something more, depending on the other elements and how to uniquely identify it. If the name of that particular input is unique, then this would work:

$('input[name="Vizualizeaza"]').hide();

subtract two times in python

import datetime

def diff_times_in_seconds(t1, t2):
    # caveat emptor - assumes t1 & t2 are python times, on the same day and t2 is after t1
    h1, m1, s1 = t1.hour, t1.minute, t1.second
    h2, m2, s2 = t2.hour, t2.minute, t2.second
    t1_secs = s1 + 60 * (m1 + 60*h1)
    t2_secs = s2 + 60 * (m2 + 60*h2)
    return( t2_secs - t1_secs)

# using it
diff_times_in_seconds( datetime.datetime.strptime( "13:23:34", '%H:%M:%S').time(),datetime.datetime.strptime( "14:02:39", '%H:%M:%S').time())

What jar should I include to use javax.persistence package in a hibernate based application?

For JPA 2.1 the javax.persistence package can be found in here:

<dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.1-api</artifactId>
   <version>1.0.0.Final</version>
</dependency>

See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions

The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.3.7.Final</version>
</dependency>

What's NSLocalizedString equivalent in Swift?

By using this way its possible to create a different implementation for different types (i.e. Int or custom classes like CurrencyUnit, ...). Its also possible to scan for this method invoke using the genstrings utility. Simply add the routine flag to the command

genstrings MyCoolApp/Views/SomeView.swift -s localize -o .

extension:

import UIKit

extension String {
    public static func localize(key: String, comment: String) -> String {
        return NSLocalizedString(key, comment: comment)
    }
}

usage:

String.localize("foo.bar", comment: "Foo Bar Comment :)")

Meaning of 'const' last in a function declaration of a class?

When you add the const keyword to a method the this pointer will essentially become a pointer to const object, and you cannot therefore change any member data. (Unless you use mutable, more on that later).

The const keyword is part of the functions signature which means that you can implement two similar methods, one which is called when the object is const, and one that isn't.

#include <iostream>

class MyClass
{
private:
    int counter;
public:
    void Foo()
    { 
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        std::cout << "Foo const" << std::endl;
    }

};

int main()
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
}

This will output

Foo
Foo const

In the non-const method you can change the instance members, which you cannot do in the const version. If you change the method declaration in the above example to the code below you will get some errors.

    void Foo()
    {
        counter++; //this works
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        counter++; //this will not compile
        std::cout << "Foo const" << std::endl;
    }

This is not completely true, because you can mark a member as mutable and a const method can then change it. It's mostly used for internal counters and stuff. The solution for that would be the below code.

#include <iostream>

class MyClass
{
private:
    mutable int counter;
public:

    MyClass() : counter(0) {}

    void Foo()
    {
        counter++;
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        counter++;    // This works because counter is `mutable`
        std::cout << "Foo const" << std::endl;
    }

    int GetInvocations() const
    {
        return counter;
    }
};

int main(void)
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
    std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << std::endl;
}

which would output

Foo
Foo const
Foo has been invoked 2 times

What is "Advanced" SQL?

When you see them spelled out in requirements they tend to include:

  • Views
  • Stored Procedures
  • User Defined Functions
  • Triggers
  • sometimes Cursors

Inner and outer joins are a must but i rarely ever see it mentioned in requirements. And it's surprising how many so-called db professionals cannot get their head around a simple outer join.

Re-ordering columns in pandas dataframe based on column name

You can also do more succinctly:

df.sort_index(axis=1)

Make sure you assign the result back:

df = df.sort_index(axis=1)

Or, do it in-place:

df.sort_index(axis=1, inplace=True)

How to retrieve field names from temporary table (SQL Server 2008)

To use information_schema and not collide with other sessions:

select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name =
    object_name(
        object_id('tempdb..#test'),
        (select database_id from sys.databases where name = 'tempdb'))

Overlaying histograms with ggplot2 in R

While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.

The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.

Single histogram:

plot_histogram <- function(df, feature) {
    plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
    geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
    geom_density(alpha=0.3, fill="red") +
    geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
    labs(x=feature, y = "Density")
    print(plt)
}

Multiple histogram:

plot_multi_histogram <- function(df, feature, label_column) {
    plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
    geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
    geom_density(alpha=0.7) +
    geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
    labs(x=feature, y = "Density")
    plt + guides(fill=guide_legend(title=label_column))
}

Usage:

Simply pass your data frame into the above functions along with desired arguments:

plot_histogram(iris, 'Sepal.Width')

enter image description here

plot_multi_histogram(iris, 'Sepal.Width', 'Species')

enter image description here

The extra parameter in plot_multi_histogram is the name of the column containing the category labels.

We can see this more dramatically by creating a dataframe with many different distribution means:

a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))

Passing data frame in as before (and widening chart using options):

options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')

enter image description here

JavaScript string and number conversion

To convert a string to a number, subtract 0. To convert a number to a string, add "" (the empty string).

5 + 1 will give you 6

(5 + "") + 1 will give you "51"

("5" - 0) + 1 will give you 6

Kill detached screen session

List screens:

screen -list

Output:

There is a screen on:
23536.pts-0.wdzee       (10/04/2012 08:40:45 AM)        (Detached)
1 Socket in /var/run/screen/S-root.

Kill screen session:

screen -S 23536 -X quit

Check file uploaded is in csv format

Mime type option is not best option for validating CSV file. I used this code this worked well in all browser

$type = explode(".",$_FILES['file']['name']);
if(strtolower(end($type)) == 'csv'){

}
else
{

}

Get Client Machine Name in PHP

gethostname() using the IP from $_SERVER['REMOTE_ADDR'] while accessing the script remotely will return the IP of your internet connection, not your computer.

How to center a (background) image within a div?

Use background-position:

background-position: 50% 50%;

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

UPDATE will not do anything if the row does not exist.

Where as the INSERT OR REPLACE would insert if the row does not exist, or replace the values if it does.