Programs & Examples On #Mknod

disable editing default value of text input

I'm not sure I understand the question correctly, but if you want to prevent people from writing in the input field you can use the disabled attribute.

<input disabled="disabled" id="price_from" value="price from ">

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

In my case, I am using a tiny .exe that reloads the referenced DLLs via Reflection. So I just do these steps which saves my day:

From project properties on solution explorer, at build tab, I choose target platfrom x86

Get the last 4 characters of a string

str = "aaaaabbbb"
newstr = str[-4:]

See : http://codepad.org/S3zjnKoD

Filter multiple values on a string column in dplyr

This can be achieved using dplyr package, which is available in CRAN. The simple way to achieve this:

  1. Install dplyr package.
  2. Run the below code
library(dplyr) 

df<- select(filter(dat,name=='tom'| name=='Lynn'), c('days','name))

Explanation:

So, once we’ve downloaded dplyr, we create a new data frame by using two different functions from this package:

filter: the first argument is the data frame; the second argument is the condition by which we want it subsetted. The result is the entire data frame with only the rows we wanted. select: the first argument is the data frame; the second argument is the names of the columns we want selected from it. We don’t have to use the names() function, and we don’t even have to use quotation marks. We simply list the column names as objects.

Task continuation on UI thread

I just wanted to add this version because this is such a useful thread and I think this is a very simple implementation. I have used this multiple times in various types if multithreaded application:

 Task.Factory.StartNew(() =>
      {
        DoLongRunningWork();
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
              { txt.Text = "Complete"; }));
      });

How do you modify the web.config appSettings at runtime?

And if you want to avoid the restart of the application, you can move out the appSettings section:

<appSettings configSource="Config\appSettings.config"/>

to a separate file. And in combination with ConfigurationSaveMode.Minimal

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);

you can continue to use the appSettings section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.

Unable to copy ~/.ssh/id_rsa.pub

Try this and it will work like a charm. I was having the same error but this approach did the trick for me:

ssh USER@REMOTE "cat file"|xclip -i

How to correctly iterate through getElementsByClassName

I followed Alohci's recommendation of looping in reverse because it's a live nodeList. Here's what I did for those who are curious...

  var activeObjects = documents.getElementsByClassName('active'); // a live nodeList

  //Use a reverse-loop because the array is an active NodeList
  while(activeObjects.length > 0) {
    var lastElem = activePaths[activePaths.length-1]; //select the last element

    //Remove the 'active' class from the element.  
    //This will automatically update the nodeList's length too.
    var className = lastElem.getAttribute('class').replace('active','');
    lastElem.setAttribute('class', className);
  }

What causes a SIGSEGV

Here is an example of SIGSEGV.

root@pierr-desktop:/opt/playGround# cat test.c
int main()
{
     int * p ;
     * p = 0x1234;
     return 0 ;
}
root@pierr-desktop:/opt/playGround# g++ -o test test.c  
root@pierr-desktop:/opt/playGround# ./test 
Segmentation fault

And here is the detail.

How to handle it?

  1. Avoid it as much as possible in the first place.

    Program defensively: use assert(), check for NULL pointer , check for buffer overflow.

    Use static analysis tools to examine your code.

    compile your code with -Werror -Wall.

    Has somebody review your code.

  2. When that actually happened.

    Examine you code carefully.

    Check what you have changed since the last time you code run successfully without crash.

    Hopefully, gdb will give you a call stack so that you know where the crash happened.


EDIT : sorry for a rush. It should be *p = 0x1234; instead of p = 0x1234;

How to change the color of the axis, ticks and labels for a plot in matplotlib

If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.

This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.

import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
    # Temporary rc parameters in effect
    fig, (ax1, ax2) = plt.subplots(1,2)
    ax1.plot(range(10))
    ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))

enter image description here

enter image description here

You can type plt.rcParams to view all available rc parameters, and use list comprehension to search for keywords:

# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]

Include CSS,javascript file in Yii Framework

here is a good solution to use CDN and offline scripts

I use this code in every application I build, so you can use this in any app.

Included Scripts:

  • main.css
  • main.js
  • jQuery
  • jQuery / CD
  • Bootstrap 3.1
  • Bootstrap 3.1 / CDN
  • Fancybox 2
  • Fancybox 2 / CDN
  • FontAwesome 4
  • FontAwesome 4 / CDN
  • Google Analytics Script

STEP1:

put this code in config/main.php

        'params'=>array(
            'cdn'=>true, // or false
...

STEP2:

create resoreses folder in root app folder and put your script there

res/
--js
--css
--img
--lib
--style
..

STEP3:

put this code in components/controller.php

public function registerDefaults() 
{
    $cs = Yii::app()->clientScript;

    if (Yii::app()->params['cdn']){
        $cs->scriptMap = array(
            'jquery.js' => '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js',
            'jquery.min.js' => '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js',
        );
        $cs->packages = array(
            'bootstrap' => array(
                'basePath' => 'application.res',
                'baseUrl' => '//netdna.bootstrapcdn.com/bootstrap/3.1.1/',
                'js' => array('js/bootstrap.min.js'),
                'css' => array('css/bootstrap.min.css'),
                'depends' => array('jquery')
            ),
        );
    } else {
        $cs->packages = array(
            'bootstrap' => array(
                'basePath' => 'application.res',
                'baseUrl' => Yii::app()->baseUrl . '/res/lib/bootstrap/',
                'js' => array('js/bootstrap.js'),
                'css' => array('css/bootstrap.css'),
                'depends' => array('jquery')
            ),
        );
    }

    $cs->registerPackage('bootstrap');

    $cs->registerCSSFile(Yii::app()->baseUrl . '/res/style/main.css');
    $cs->registerScriptFile(Yii::app()->baseUrl . '/res/js/main.js');
}

public function registerFancybox($buttons = false, $thumbs = false) 
{
    $cs = Yii::app()->clientScript;

    $cs->packages = array(
        'fancybox' => array(
            'basePath' => 'application.res',
            'baseUrl' => Yii::app()->baseUrl . '/res/lib/fancybox/',
            'js' => array('lib/jquery.mousewheel-3.0.6.pack.js', 'source/jquery.fancybox.pack.js'),
            'css' => array('source/jquery.fancybox.css'),
            'depends' => array('jquery')
        ),
        'fancybox-buttons' => array(
            'basePath' => 'application.res',
            'baseUrl' => Yii::app()->baseUrl . '/res/lib/fancybox/source/helpers/',
            'js' => array('jquery.fancybox-buttons.js'),
            'css' => array('jquery.fancybox-buttons.css'),
        ),
        'fancybox-thumbs' => array(
            'basePath' => 'application.res',
            'baseUrl' => Yii::app()->baseUrl . '/res/lib/fancybox/source/helpers/',
            'js' => array('jquery.fancybox-thumbs.js'),
            'css' => array('jquery.fancybox-thumbs.css'),
        )
    );

    $cs->registerPackage('fancybox');
    if ($buttons)
        $cs->registerPackage('fancybox-buttons');
    if ($thumbs)
        $cs->registerPackage('fancybox-thumbs');
}

public function registerFontAwesome(){

    $cs = Yii::app()->clientScript;

    if (Yii::app()->params['cdn']):
        $cs->packages = array(
            'fontAwesome' => array(
                'basePath' => 'application.res',
                'baseUrl' => '//netdna.bootstrapcdn.com/font-awesome/4.0.0/',
                'css' => array('css/font-awesome.min.css'),
            )
        );
    else:
        $cs->packages = array(
            'fontAwesome' => array(
                'basePath' => 'application.res',
                'baseUrl' => Yii::app()->baseUrl . '/res/lib/font-awesome/',
                'css' => array('/css/font-awesome.min.css'),
            )
        );
    endif;

    $cs->registerPackage('fontAwesome');
}

public function registerGoogleAnalytics()
{
    if($this->config('settings_google_analytics_id')){
        Yii::app()->clientScript->registerScript('GA',"
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

            ga('create', '".Yii::app()->params['cdn']."', '{$_SERVER['SERVER_NAME']}');
            ga('send', 'pageview');
        ");
    }
}

STEP4:

call the functions like this in //layouts/main.php

Yii::app()->getController()->registerDefaults();
Yii::app()->getController()->registerFontAwesome();
Yii::app()->getController()->registerGoogleAnalytics();

Gradient borders

I agree with szajmon. The only problem with his and Quentin's answers is cross-browser compatibility.

HTML:

<div class="g">
    <div>bla</div>
</div>

CSS:

.g {
background-image: -webkit-linear-gradient(300deg, white, black, white); /* webkit browsers (Chrome & Safari) */
background-image: -moz-linear-gradient(300deg, white, black, white); /* Mozilla browsers (Firefox) */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#000000', gradientType='1'); /* Internet Explorer */
background-image: -o-linear-gradient(300deg,rgb(255,255,255),rgb(0,0,0) 50%,rgb(255,255,255) 100%); /* Opera */
}

.g > div { background: #fff; }

sed whole word search and replace

\b in regular expressions match word boundaries (i.e. the location between the first word character and non-word character):

$ echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
no bar embarassment

How do I get the HTTP status code with jQuery?

I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.

The best way to combat this is to call the .always chain method and do a bit of cleaning up. Here is my code.

$.ajax({
        ...
    }).always(function(data, textStatus, xhr) {
        var responseCode = null;
        if (textStatus === "error") {
            // data variable is actually xhr
            responseCode = data.status;
            if (data.responseText) {
                try {
                    data = JSON.parse(data.responseText);
                } catch (e) {
                    // Ignore
                }
            }
        } else {
            responseCode = xhr.status;
        }

        console.log("Response code", responseCode);
        console.log("JSON Data", data);
    });

How to set RelativeLayout layout params in code not in xml?

Just a basic example:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);

As you can see, this is what you have to do:

  1. Create a RelativeLayout.LayoutParams object.
  2. Use addRule(int) or addRule(int, int) to set the rules. The first method is used to add rules that don't require values.
  3. Set the parameters to the view (in this case, to each button).

Most efficient way to convert an HTMLCollection to an Array

This is my personal solution, based on the information here (this thread):

var Divs = new Array();    
var Elemns = document.getElementsByClassName("divisao");
    try {
        Divs = Elemns.prototype.slice.call(Elemns);
    } catch(e) {
        Divs = $A(Elemns);
    }

Where $A was described by Gareth Davis in his post:

function $A(iterable) {
  if (!iterable) return [];
  if ('toArray' in Object(iterable)) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

If browser supports the best way, ok, otherwise will use the cross browser.

How to get the last char of a string in PHP?

Or by direct string access:

$string[strlen($string)-1];

Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions.

As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

Automatic prune with Git fetch or pull

Since git 1.8.5 (Q4 2013):

"git fetch" (hence "git pull" as well) learned to check "fetch.prune" and "remote.*.prune" configuration variables and to behave as if the "--prune" command line option was given.

That means that, if you set remote.origin.prune to true:

git config remote.origin.prune true

Any git fetch or git pull will automatically prune.

Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename misbehave.
See "How do I rename a git remote?".


See more at commit 737c5a9:

Without "git fetch --prune", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune".

To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "fetch.prune" and "remote.<name>.prune":

  • "fetch.prune" allows to enable prune for all fetch operations.
  • "remote.<name>.prune" allows to change the behaviour per remote.

The latter will naturally override the former, and the --[no-]prune option from the command line will override the configured default.

Since --prune is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.

How does the modulus operator work?

in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:

5 % 2 = 1
13 % 5 = 3

With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).

To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

You are checking Parent properties for null in your delegate. The same should work with lambda expressions too.

List<AnalysisObject> analysisObjects = analysisObjectRepository
        .FindAll()
        .Where(x => 
            (x.ID == packageId) || 
            (x.Parent != null &&
                (x.Parent.ID == packageId || 
                (x.Parent.Parent != null && x.Parent.Parent.ID == packageId)))
        .ToList();

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1 https://github.com/user/repo.git

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git

Can I find events bound on an element with jQuery?

When I pass a little complex DOM query to $._data like this: $._data($('#outerWrap .innerWrap ul li:last a'), 'events') it throws undefined in the browser console.

So I had to use $._data on the parent div: $._data($('#outerWrap')[0], 'events') to see the events for the a tags. Here is a JSFiddle for the same: http://jsfiddle.net/giri_jeedigunta/MLcpT/4/

How do I make a dictionary with multiple keys to one value?

It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.

let's go to the code example,

In [6]: a = 10

In [7]: id(a)
Out[7]: 10914656

In [8]: b = 10

In [9]: id(b)
Out[9]: 10914656

In [10]: c = 11

In [11]: id(c)
Out[11]: 10914688

In [12]: d = 21

In [13]: id(d)
Out[13]: 10915008

In [14]: e = 11

In [15]: id(e)
Out[15]: 10914688

In [16]: e = 21

In [17]: id(e)
Out[17]: 10915008

In [18]: e is d
Out[18]: True
In [19]: e = 30

In [20]: id(e)
Out[20]: 10915296

From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.

so any variable which is having same value shares the memory.

Not for list and dictionary objects

let's come to your question.

when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.

you can simply use it like this

In [49]: dictionary = {
    ...:     'k1':1,
    ...:     'k2':1,
    ...:     'k3':2,
    ...:     'k4':2}
    ...:     
    ...:     

In [50]: id(dictionary['k1'])
Out[50]: 10914368

In [51]: id(dictionary['k2'])
Out[51]: 10914368

In [52]: id(dictionary['k3'])
Out[52]: 10914400

In [53]: id(dictionary['k4'])
Out[53]: 10914400

From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P

The requested resource does not support HTTP method 'GET'

just use this attribute

[System.Web.Http.HttpGet]

not need this line of code:

[System.Web.Http.AcceptVerbs("GET", "POST")]

How to prevent downloading images and video files from my website?

Don't post them to your site.

Otherwise it is not possible.

Android on-screen keyboard auto popping up

You can use either this in the onCreate() method of the activity

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 

or paste this code in the Activity tags in AndroidManifest.xml

android:windowSoftInputMode="stateVisible"

How to get data by SqlDataReader.GetValue by column name

Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]); 

How can I insert data into a MySQL database?

Here is OOP:

import MySQLdb


class Database:

    host = 'localhost'
    user = 'root'
    password = '123'
    db = 'test'

    def __init__(self):
        self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
        self.cursor = self.connection.cursor()

    def insert(self, query):
        try:
            self.cursor.execute(query)
            self.connection.commit()
        except:
            self.connection.rollback()



    def query(self, query):
        cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
        cursor.execute(query)

        return cursor.fetchall()

    def __del__(self):
        self.connection.close()


if __name__ == "__main__":

    db = Database()

    #CleanUp Operation
    del_query = "DELETE FROM basic_python_database"
    db.insert(del_query)

    # Data Insert into the table
    query = """
        INSERT INTO basic_python_database
        (`name`, `age`)
        VALUES
        ('Mike', 21),
        ('Michael', 21),
        ('Imran', 21)
        """

    # db.query(query)
    db.insert(query)

    # Data retrieved from the table
    select_query = """
        SELECT * FROM basic_python_database
        WHERE age = 21
        """

    people = db.query(select_query)

    for person in people:
        print "Found %s " % person['name']

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

How do you run PowerShell built-in scripts inside of your scripts?

How do you use built-in scripts like

Get-Location
pwd
ls
dir
split-path
::etc...

Those are ran by your computer, automatically checking the path of the script.

Similarly, I can run my custom scripts by just putting the name of the script in the script-block

::sid.ps1 is a PS script I made to find the SID of any user
::it takes one argument, that argument would be the username
echo $(sid.ps1 jowers)


(returns something like)> S-X-X-XXXXXXXX-XXXXXXXXXX-XXX-XXXX


$(sid.ps1 jowers).Replace("S","X")

(returns same as above but with X instead of S)

Go on to the powershell command line and type

> $profile

This will return the path to a file that our PowerShell command line will execute every time you open the app.

It will look like this

C:\Users\jowers\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

Go to Documents and see if you already have a WindowsPowerShell directory. I didn't, so

> cd \Users\jowers\Documents
> mkdir WindowsPowerShell
> cd WindowsPowerShell
> type file > Microsoft.PowerShellISE_profile.ps1

We've now created the script that will launch every time we open the PowerShell App.

The reason we did that was so that we could add our own folder that holds all of our custom scripts. Let's create that folder and I'll name it "Bin" after the directories that Mac/Linux hold its scripts in.

> mkdir \Users\jowers\Bin

Now we want that directory to be added to our $env:path variable every time we open the app so go back to the WindowsPowerShell Directory and

> start Microsoft.PowerShellISE_profile.ps1

Then add this

$env:path += ";\Users\jowers\Bin"

Now the shell will automatically find your commands, as long as you save your scripts in that "Bin" directory.

Relaunch the powershell and it should be one of the first scripts that execute.

Run this on the command line after reloading to see your new directory in your path variable:

> $env:Path

Now we can call our scripts from the command line or from within another script as simply as this:

$(customScript.ps1 arg1 arg2 ...)

As you see we must call them with the .ps1 extension until we make aliases for them. If we want to get fancy.

How to select a column name with a space in MySQL

If double quotes does not work , try including the string within square brackets.

For eg:

SELECT "Business Name","Other Name" FROM your_Table

can be changed as

SELECT [Business Name],[Other Name] FROM your_Table

Adding a default value in dropdownlist after binding with database

You can add it programmatically or in the markup, but if you add it programmatically, rather than Add the item, you should Insert it as position zero so that it is the first item:

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");

The default item is expected to be the first item in the list. If you just Add it, it will be on the bottom and will not be selected by default.

Pass C# ASP.NET array to Javascript array

You can use ClientScript.RegisterStartUpScript to inject javascript into the page on Page_Load.

Here's a link to MSDN reference: http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Here's the code in Page_Load:

  List<string> tempString = new List<string>();
  tempString.Add("Hello");
  tempString.Add("World");

  StringBuilder sb = new StringBuilder();
  sb.Append("<script>");
  sb.Append("var testArray = new Array;");
  foreach(string str in tempString)
  {
    sb.Append("testArray.push('" + str + "');");
  }
  sb.Append("</script>");

  ClientScript.RegisterStartupScript(this.GetType(), "TestArrayScript", sb.ToString());

Notes: Use StringBuilder to build the script string as it will probably be long.

And here's the Javascript that checks for the injected array "testArray" before you can work with it:

if (testArray)
{
  // do something with testArray
}

There's 2 problems here:

  1. Some consider this intrusive for C# to inject Javascript

  2. We'll have to declare the array at a global context

If you can't live with that, another way would be to have the C# code save the Array into View State, then have the JavaScript use PageMethods (or web services) to call back to the server to get that View State object as an array. But I think that may be overkill for something like this.

Where are Docker images stored on the host machine?

I can answer this question only for Ubuntu users:

The root directory of docker can be found when you run the command docker info

Docker directory will be given in this line: "Docker Root Dir: /var/lib/docker"

About the docker images, they are stored inside the docker directory: /var/lib/docker/aufs/diff/

Remember these things are not same in all version of docker. Currently, I am using 1.12.3.

How to create a DataFrame from a text file in Spark

I know I am quite late to answer this but I have come up with a different answer:

val rdd = sc.textFile("/home/training/mydata/file.txt")

val text = rdd.map(lines=lines.split(",")).map(arrays=>(ararys(0),arrays(1))).toDF("id","name").show 

How to achieve pagination/table layout with Angular.js?

I use this solution:

It's a bit more concise since I use: ng-repeat="obj in objects | filter : paginate" to filter the rows. Also made it working with $resource:

http://plnkr.co/edit/79yrgwiwvan3bAG5SnKx?p=preview

How to get first character of a string in SQL?

SELECT SUBSTR(thatColumn, 1, 1) As NewColumn from student

@AspectJ pointcut for all methods of a class with specific annotation

I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.

@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
    /**
     * It is the parameter is to show arguments in the method or the class.
     */
    boolean showArguments() default false;
}


@Aspect
@Component
public class AnnotationLoggerAspect {
    
    @Autowired 
    private Logger logger;  
    
    private static final String METHOD_NAME   = "METHOD NAME: {} ";
    private static final String ARGUMENTS     = "ARGS: {} ";
    
    @Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
    public void logAdviceExecutionBefore(JoinPoint joinPoint){  
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
        AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
        if(annotationLogger!= null) {
            StringBuilder annotationLoggerFormat = new StringBuilder();
            List<Object> annotationLoggerArguments = new ArrayList<>();
            annotationLoggerFormat.append(METHOD_NAME);
            annotationLoggerArguments.add(codeSignature.getName());
            
            if (annotationLogger.showArguments()) {
                annotationLoggerFormat.append(ARGUMENTS);
                List<?> argumentList = Arrays.asList(joinPoint.getArgs());
                annotationLoggerArguments.add(argumentList.toString());
            }
            logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
        }
    }
    
    private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
        AnnotationLogger annotationLogger = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = joinPoint.getTarget().getClass().
                    getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());
            
            if (method.isAnnotationPresent(AnnotationLogger.class)){
                annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
            }else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
                annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
            }
            return annotationLogger;
        }catch(Exception e) {
            return annotationLogger;
        }
    }
}

Fit cell width to content

I'm not sure if I understand your question, but I'll take a stab at it:

_x000D_
_x000D_
td {
    border: 1px solid #000;
}

tr td:last-child {
    width: 1%;
    white-space: nowrap;
}
_x000D_
<table style="width: 100%;">
    <tr>
        <td class="block">this should stretch</td>
        <td class="block">this should stretch</td>
        <td class="block">this should be the content width</td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

Setting cursor at the end of any text of a textbox

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

Android RelativeLayout programmatically Set "centerInParent"

I have done for

1. centerInParent

2. centerHorizontal

3. centerVertical

with true and false.

private void addOrRemoveProperty(View view, int property, boolean flag){
    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
    if(flag){
        layoutParams.addRule(property);
    }else {
        layoutParams.removeRule(property);
    }
    view.setLayoutParams(layoutParams);
}

How to call method:

centerInParent - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);

centerInParent - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);

centerHorizontal - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);

centerHorizontal - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);

centerVertical - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);

centerVertical - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);

Hope this would help you.

How to create a simple proxy in C#?

Socks4 is a very simple protocol to implement. You listen for the initial connection, connect to the host/port that was requested by the client, send the success code to the client then forward the outgoing and incoming streams across sockets.

If you go with HTTP you'll have to read and possibly set/remove some HTTP headers so that's a little more work.

If I remember correctly, SSL will work across HTTP and Socks proxies. For a HTTP proxy you implement the CONNECT verb, which works much like the socks4 as described above, then the client opens the SSL connection across the proxied tcp stream.

Call a stored procedure with parameter in c#

Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money

public void SaveTransaction(Transaction transaction) 
{
    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
    {
        using (var cmd = new SqlCommand("spAddTransaction", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(transaction, null));
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

How to add Class in <li> using wp_nav_menu() in Wordpress?

How about just using str_replace function, if you just want to "Add Classes":

<?php
    echo str_replace( '<li class="', '<li class="myclass ',
        wp_nav_menu(
            array(
                'theme_location'    => 'main_menu',
                'container'         => false,
                'items_wrap'        => '<ul>%3$s</ul>',
                'depth'             => 1,
                'echo'              => false
            )
        )
    );
?>

Tough it is a quick fix for one-level menus or the menus that you want to add Classes to all of <li> elements and is not recommended for more complex menus

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

How to set an image's width and height without stretching it?

What I can think of is to stretch either width or height and let it resize in ratio-aspect. There will be some white space on the sides. Something like how a Wide screen displays a resolution of 1024x768.

How to see remote tags?

You can list the tags on remote repository with ls-remote, and then check if it's there. Supposing the remote reference name is origin in the following.

git ls-remote --tags origin

And you can list tags local with tag.

git tag

You can compare the results manually or in script.

What is the easiest way to clear a database from the CLI with manage.py in Django?

Quickest (drops and creates all tables including data):

./manage.py reset appname | ./manage.py dbshell

Caution:

  • Might not work on Windows correctly.
  • Might keep some old tables in the db

Alternative to google finance api

If you are still looking to use Google Finance for your data you can check this out.

I recently needed to test if SGX data is indeed retrievable via google finance (and of course i met with the same problem as you)

Can anonymous class implement interface?

The best solution is just not to use anonymous classes.

public class Test
{
    class DummyInterfaceImplementor : IDummyInterface
    {
        public string A { get; set; }
        public string B { get; set; }
    }

    public void WillThisWork()
    {
        var source = new DummySource[0];
        var values = from value in source
                     select new DummyInterfaceImplementor()
                     {
                         A = value.A,
                         B = value.C + "_" + value.D
                     };

        DoSomethingWithDummyInterface(values.Cast<IDummyInterface>());

    }

    public void DoSomethingWithDummyInterface(IEnumerable<IDummyInterface> values)
    {
        foreach (var value in values)
        {
            Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
        }
    }
}

Note that you need to cast the result of the query to the type of the interface. There might be a better way to do it, but I couldn't find it.

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.

In the case of the first block:

filecontent()
{
    setGUI();
    setRegister();
    showfile();
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

You would have to include a try catch block:

filecontent()
{
    setGUI();
    setRegister();
    try {
        showfile();
    }
    catch (IOException e) {
        // Do something here
    }
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

In the case of the second:

public void actionPerformed(ActionEvent ae)
{
    if (ae.getSource() == submit)
    {
        showfile();
    }
}

You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:

public void actionPerformed(ActionEvent ae)
{
    if(ae.getSource()==submit)
    {
        try {
            showfile();
        }
        catch (IOException e) {
            // Do something here
        }
    }
}

Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.

If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

I ran into this issue with a Grails install.

The problem was my JAVA_HOME was c:\sun\jdk\ and my PATH has %JAVA_HOME%bin

I changed it to: JAVA_HOME= "c:\sun\jdk" and PATH="%JAVA_HOME%\bin"

It worked after that.

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

Visual Studio Code - Convert spaces to tabs

If you want to use tabs instead of spaces

Try this:

  1. Go to File ? Preferences ? Settings or just press Ctrl + ,
  2. In the Search settings bar on top insert editor.insertSpaces
  3. You will see something like this: Editor: Insert Spaces and it will be probably checked. Just uncheck it as show in image below

Editor: Insert Spaces

  1. Reload Visual Studio Code (Press F1 ? type reload window ? press Enter)

If it doesn't worked try this:

It's probably because of installed plugin JS-CSS-HTML Formatter

(You can check it by going to File ? Preferences ? Extensions or just pressing Ctrl + Shift + X, in the Enabled list you will find JS-CSS-HTML Formatter)

If so you can modify this plugin:

  1. Press F1 ? type Formatter config ? press Enter (it will open the file formatter.json)
  2. Modify the file like this:
 4|    "indent_size": 1,
 5|    "indent_char": "\t"
——|
24|    "indent_size": 1,
25|    "indentCharacter": "\t",
26|    "indent_char": "\t",
——|
34|    "indent_size": 1,
35|    "indent_char": "\t",
36|    "indent_character": "\t"
  1. Save it (Go to File ? Save or just press Ctrl + S)
  2. Reload Visual Studio Code (Press F1 ? type reload window ? press Enter)

How can I group by date time column without taking time into consideration

I believe you need to group by , in that day of the month of the year . so why not using TRUNK_DATE functions . The way it works is described below :

Group By DATE_TRUNC('day' , 'occurred_at_time')

Converting File to MultiPartFile

This is a solution without creating manually a file on disc :

MultipartFile fichier = new MockMultipartFile("fileThatDoesNotExists.txt",
            "fileThatDoesNotExists.txt",
            "text/plain",
            "This is a dummy file content".getBytes(StandardCharsets.UTF_8));

ReCaptcha API v2 Styling

Unfortunately we cant style reCaptcha v2, but it is possible to make it look better, here is the code:

Click here to preview

.g-recaptcha-outer{
    text-align: center;
    border-radius: 2px;
    background: #f9f9f9;
    border-style: solid;
    border-color: #37474f;
    border-width: 1px;
    border-bottom-width: 2px;
}
.g-recaptcha-inner{
    width: 154px;
    height: 82px;
    overflow: hidden;
    margin: 0 auto;
}
.g-recaptcha{
    position:relative;
    left: -2px;
    top: -1px;
}

<div class="g-recaptcha-outer">
    <div class="g-recaptcha-inner">
        <div class="g-recaptcha" data-size="compact" data-sitekey="YOUR KEY"></div>
    </div>
</div>

How to check permissions of a specific directory?

Here is the short answer:

$ ls -ld directory

Here's what it does:

-d, --directory
    list directory entries instead of contents, and do not dereference symbolic links

You might be interested in manpages. That's where all people in here get their nice answers from.

refer to online man pages

How to redirect output of an already running process

Dupx

Dupx is a simple *nix utility to redirect standard output/input/error of an already running process.

Motivation

I've often found myself in a situation where a process I started on a remote system via SSH takes much longer than I had anticipated. I need to break the SSH connection, but if I do so, the process will die if it tries to write something on stdout/error of a broken pipe. I wish I could suspend the process with ^Z and then do a

bg %1 >/tmp/stdout 2>/tmp/stderr 

Unfortunately this will not work (in shells I know).

http://www.isi.edu/~yuri/dupx/

Groovy Shell warning "Could not open/create prefs root node ..."

I was getting the following message:

Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002

and it was gone after creating one of these registry keys, mine is 64 bit so I tried only that.

32 bit Windows
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

64 bit Windows
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

The action or event has been blocked by Disabled Mode

I solved this with Access options.

Go to the Office Button --> Access Options --> Trust Center --> Trust Center Settings Button --> Message Bar

In the right hand pane I selected the radio button "Show the message bar in all applications when content has been blocked."

Closed Access, reopened the database and got the warning for blocked content again.

Call to undefined function oci_connect()

Things to Make sure

  1. Whenever you connecting Oracle Database , try to use 32 Bit oracle client libraries, Since XAMP PHP is compiled with 32 Bit(Though you have 64 Bit windows Machine)
  2. Download Oracle Client from Download From here

  3. Paste it in C:\instantclient_12_1

  4. Then Set the path to above in System Environment Variable
  5. Then Go to C:\xampp\php\php.ini and uncomment extension=php_oci8_12c.dll
  6. Then Restart the XAMP and it should work without any Issue.

Oracle Sql get only month and year in date datatype

Easiest solution is to create the column using the correct data type: DATE

For example:

  1. Create table:

    create table test_date (mydate date);

  2. Insert row:

    insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));

To get the month and year, do as follows:

select to_char(mydate, 'MM-YYYY') from test_date;

Your result will be as follows: 01-2011

Another cool function to use is "EXTRACT"

select extract(year from mydate) from test_date;

This will return: 2011

How can I make directory writable?

  • chmod +w <directory> or chmod a+w <directory> - Write permission for user, group and others

  • chmod u+w <directory> - Write permission for user

  • chmod g+w <directory> - Write permission for group

  • chmod o+w <directory> - Write permission for others

How do I compare two strings in python?

For that, you can use default difflib in python

from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

then call similar() as

similar(string1, string2)

it will return compare as ,ratio >= threshold to get match result

Is right click a Javascript event?

Most of the given solutions using the mouseup or contextmenu events fire every time the right mouse button goes up, but they don't check wether it was down before.


If you are looking for a true right click event, which only fires when the mouse button has been pressed and released within the same element, then you should use the auxclick event. Since this fires for every none-primary mouse button you should also filter other events by checking the button property.

_x000D_
_x000D_
window.addEventListener("auxclick", (event) => {
  if (event.button === 2) alert("Right click");
});
_x000D_
_x000D_
_x000D_

You can also create your own right click event by adding the following code to the start of your JavaScript:

{
  const rightClickEvent = new CustomEvent('rightclick', { bubbles: true });
  window.addEventListener("auxclick", (event) => {
    if (event.button === 2) {
      event.target.dispatchEvent(rightClickEvent);
    }
  });
}

You can then listen for right click events via the addEventListener method like so:

your_element.addEventListener("rightclick", your_function);

Read more about the auxclick event on MDN.

How do I reverse a commit in git?

Or you can try using git revert http://www.kernel.org/pub/software/scm/git/docs/git-revert.html. I think something like git revert HEAD~1 -m 1 will revert your last commit (if it's still the last commit).

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

Move the session_start(); to top of the page always.

<?php
@ob_start();
session_start();
?>

The type or namespace name 'DbContext' could not be found

I had the same issue... Installing the EF from Package Manager Console worked for me

the command was: Install-Package EntityFramework

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

cd into directory without having permission

chmod +x openfire worked for me. It adds execution permission to the openfire folder.

Marker in leaflet, click event

I found the solution:

function onClick(e) {alert(this.getLatLng());}

used the method getLatLng() of the marker

Printing 2D array in matrix format

I wrote extension method

public static string ToMatrixString<T>(this T[,] matrix, string delimiter = "\t")
{
    var s = new StringBuilder();

    for (var i = 0; i < matrix.GetLength(0); i++)
    {
        for (var j = 0; j < matrix.GetLength(1); j++)
        {
            s.Append(matrix[i, j]).Append(delimiter);
        }

        s.AppendLine();
    }

    return s.ToString();
}

To use just call the method

results.ToMatrixString();

Replacing blank values (white space) with NaN in pandas

This is not an elegant solution, but what does seem to work is saving to XLSX and then importing it back. The other solutions on this page did not work for me, unsure why.

data.to_excel(filepath, index=False)
data = pd.read_excel(filepath)

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

Can you get round this by calling System.load() programmatically to load your native library? This method (unlike System.loadLibrary()) allows you to specify an absolute path.

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

MySQL integer field is returned as string in PHP

In my project I usually use an external function that "filters" data retrieved with mysql_fetch_assoc.

You can rename fields in your table so that is intuitive to understand which data type is stored.

For example, you can add a special suffix to each numeric field: if userid is an INT(11) you can rename it userid_i or if it is an UNSIGNED INT(11) you can rename userid_u. At this point, you can write a simple PHP function that receive as input the associative array (retrieved with mysql_fetch_assoc), and apply casting to the "value" stored with those special "keys".

How to solve javax.net.ssl.SSLHandshakeException Error?

First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, using OpenSSL to download it, or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)

Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At $JAVA_HOME/jre/lib/security/ for JREs or $JAVA_HOME/lib/security for JDKs, there's a file named cacerts, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:

keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>

It will most likely ask you for a password. The default password as shipped with Java is changeit. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key).

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

I'd suggest a different approach to this question. Maybe it's not the most efficient one, but I think it's the easiest to apply and requires very little code. Writing the next code in your first activity (log in activity, in my case) won't let the user go back to previously launched activities after logging out.

@Override
public void onBackPressed() {
    // disable going back to the MainActivity
    moveTaskToBack(true);
}

I'm assuming that LoginActivity is finished just after the user logs in, so that he can't go back to it later by pressing the back button. Instead, the user must press a log out button inside the app in order to log out properly. What this log out button would implement is a simple intent as follows:

Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();

All suggestions are welcome.

JPA CascadeType.ALL does not delete orphans

If you are using it with Hibernate, you'll have to explicitly define the annotation CascadeType.DELETE_ORPHAN, which can be used in conjunction with JPA CascadeType.ALL.

If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records.

execution sequence

  1. fetch main row to be deleted
  2. fetch child elements
  3. delete all child elements
  4. delete main row
  5. close session

With JPA 2.0, you can now use the option orphanRemoval = true

@OneToMany(mappedBy="foo", orphanRemoval=true)

CentOS: Copy directory to another directory

cp -r /home/server/folder/test /home/server/

Fill formula down till last row in column

For people with a similar question and find this post (like I did); you can do this even without lastrow if your dataset is formatted as a table.

Range("tablename[columnname]").Formula = "=G3&"",""&L3"

Making it a true one liner. Hope it helps someone!

Need table of key codes for android and presenter

List Of Key codes:

a - z-> 29 - 54

"0" - "9"-> 7 - 16

BACK BUTTON - 4, MENU BUTTON - 82

UP-19, DOWN-20, LEFT-21, RIGHT-22

SELECT (MIDDLE) BUTTON - 23

SPACE - 62, SHIFT - 59, ENTER - 66, BACKSPACE - 67

How can I add a volume to an existing Docker container?

The best way is to copy all the files and folders inside a directory on your local file system by: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH

SRC_PATH is on container DEST_PATH is on localhost

Then do docker-compose down attach a volume to the same DEST_PATH and run Docker containers by using docker-compose up -d

Add volume by following in docker-compose.yml

volumes:
 - DEST_PATH:SRC_PATH

Java 8 Distinct by property

The Most simple code you can write:

    persons.stream().map(x-> x.getName()).distinct().collect(Collectors.toList());

<button> background image

Delete "button" before # rock:

button #rock {
    background: url(img/rock.png) no-repeat;
} 

Worked for me in Google Chrome.

Export a graph to .eps file with R

The postscript() device allows creation of EPS, but only if you change some of the default values. Read ?postscript for the details.

Here is an example:

postscript("foo.eps", horizontal = FALSE, onefile = FALSE, paper = "special")
plot(1:10)
dev.off()

PivotTable's Report Filter using "greater than"

One way to do this is to pull your field into the rows section of the pivot table from the Filter section. Then group the values that you want to keep into a group, using the group option on the menu. After that is completed, drag your field back into the Filters section. The grouping will remain and you can check or uncheck one box to remove lots of values.

Add a new element to an array without specifying the index in Bash

Yes there is:

ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')

Bash Reference Manual:

In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.

How to use LINQ Distinct() with multiple fields

Use the Key keyword in your select will work, like below.

product.Select(m => new {Key m.CategoryId, Key m.CategoryName}).Distinct();

I realize this is bringing up an old thread but figured it might help some people. I generally code in VB.NET when working with .NET so Key may translate differently into C#.

Printing out all the objects in array list

Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Override
public String toString() {
    return "Student No: " + this.getStudentNo() + 
           ", Student Name: " + this.getStudentName();
}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();

// You can directly print your ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(Student student: students) {
    System.out.println(student);  // Will invoke overrided `toString()` method
}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.

Laravel 5: Display HTML with Blade

You can use {!! $text !!} for render HTML code in Laravel

{!! $text !!}

If you use

{{ $text }}

It will not render HTML code and print as a string.

How do I use vim registers?

One of my favorite parts about registers is using them as macros!

Let's say you are dealing with a tab-delimited value file as such:

ID  Df  %Dev    Lambda
1   0   0.000000    0.313682
2   1   0.023113    0.304332
3   1   0.044869    0.295261
4   1   0.065347    0.286460
5   1   0.084623    0.277922
6   1   0.102767    0.269638
7   1   0.119845    0.261601

Now you decide that you need to add a percentage sign at the end of the %Dev field (starting from 2nd line). We'll make a simple macro in the (arbitrarily selected) m register as follows:

  1. Press: qm: To start recording macro under m register.

  2. EE: Go to the end of the 3rd column.

  3. a: Insert mode to append to the end of this column.

  4. %: Type the percent sign we want to add.

  5. <ESC>: Get back into command mode.

  6. j0: Go to beginning of next line.

  7. q: Stop recording macro

We can now just type @m to run this macro on the current line. Furthermore, we can type @@ to repeat, or 100@m to do this 100 times! Life's looking pretty good.

At this point you should be saying, "But what does this have to do with registers?"

Excellent point. Let's investigate what is in the contents of the m register by typing "mp. We then get the following:

EEa%<ESC>j0

At first this looks like you accidentally opened a binary file in notepad, but upon second glance, it's the exact sequence of characters in our macro!

You are a curious person, so let's do something interesting and edit this line of text to insert a ! instead of boring old %.

EEa!<ESC>j0

Then let's yank this into the n register by typing B"nyE. Then, just for kicks, let's run the n macro on a line of our data using @n....

It added a !.

Essentially, running a macro is like pressing the exact sequence of keys in that macro's register. If that isn't a cool register trick, I'll eat my hat.

Java 8 lambda Void argument

The syntax you're after is possible with a little helper function that converts a Runnable into Action<Void, Void> (you can place it in Action for example):

public static Action<Void, Void> action(Runnable runnable) {
    return (v) -> {
        runnable.run();
        return null;
    };
}

// Somewhere else in your code
 Action<Void, Void> action = action(() -> System.out.println("foo"));

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

Removing viewcontrollers from navigation stack

Use this

if let navVCsCount = navigationController?.viewControllers.count {
    navigationController?.viewControllers.removeSubrange(Range(2..<navVCsCount - 1))
}

It will take care of ViewControllers of navigationController. viewControllers and also a navigationItems stacked in navigationBar.

Note: Be sure to call it at least after viewDidAppear

Call angularjs function using jquery/javascript

You can use following:

angular.element(domElement).scope() to get the current scope for the element

angular.element(domElement).injector() to get the current app injector

angular.element(domElement).controller() to get a hold of the ng-controller instance.

Hope that might help

How to change date format using jQuery?

I dont think you need to use jQuery at all, just simple JavaScript...

Save the date as a string:

dte = fecha.value;//2014-01-06

Split the string to get the day, month & year values...

dteSplit = dte.split("-");
yr = dteSplit[0][2] + dteSplit[0][3]; //special yr format, take last 2 digits
month = dteSplit[1];
day = dteSplit[2];

Rejoin into final date string:

finalDate = month+"-"+day+"-"+year

Select element by exact match of its content

An one-liner that works with alternative libraries to jQuery:

$('p').filter((i, p) => $(p).text().trim() === "hello").css('font-weight', 'bold');

And this is the equivalent to a jQuery's a:contains("pattern") selector:

var res = $('a').filter((i, a) => $(a).text().match(/pattern/));

Onclick CSS button effect

Push down the whole button. I suggest this it is looking nice in button.

#button:active {
    position: relative;
    top: 1px;
}

if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.

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

In c# you can simply say:

if (myObj is Car) {

}

require is not defined? Node.js

In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).

But, you won't be running a web server in your browser as that is not something the browser has the capability to do.


You may be interested in browserify which lets you use node-style modules in a browser using require() statements.

MSVCP140.dll missing

Your friend's PC is missing the runtime support DLLs for your program:

How to convert a Title to a URL slug in jQuery?

For people already using lodash

Most of these example are really good and cover a lot of cases. But if you 'know' that you only have English text, here's my version that's super easy to read :)

_.words(_.toLower(text)).join('-')

R memory management / cannot allocate vector of size n Mb

I followed to the help page of memory.limit and found out that on my computer R by default can use up to ~ 1.5 GB of RAM and that the user can increase this limit. Using the following code,

>memory.limit()
[1] 1535.875
> memory.limit(size=1800)

helped me to solve my problem.

Split string into string array of single characters

Most likely you're looking for the ToCharArray() method. However, you will need to do slightly more work if a string[] is required, as you noted in your post.

    string str = "this is a test.";
    char[] charArray = str.ToCharArray();
    string[] strArray = str.Select(x => x.ToString()).ToArray();

Edit: If you're worried about the conciseness of the conversion, I suggest you make it into an extension method.

public static class StringExtensions
{
    public static string[] ToStringArray(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return null;

        return s.Select(x => x.ToString()).ToArray();
    }
} 

Flatten List in LINQ

iList.SelectMany(x => x).ToArray()

git with IntelliJ IDEA: Could not read from remote repository

Not a solution / workaround but perhaps an answer to the question 'what could be the problem':

Gitlab and the 'jetbrains built in ssh library' do not work well together. The library wants to use SHA1 based key exchange algorithm where gitlab (default) only allows SHA2 based key exchange algorithm's.

This was reported for at least TeamCity (https://youtrack.jetbrains.com/issue/TW-47704).

The fact that it also might be the cause for your pull/push problem in IntelliJ, and also my push-problem in PhpStorm is based on the ASSUMPTION jetbrains use the same 'built in library' for all their software.

Move / Copy File Operations in Java

Not yet, but the New NIO (JSR 203) will have support for these common operations.

In the meantime, there are a few things to keep in mind.

File.renameTo generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.

When a rename doesn't work you will need to actually copy the file (deleting the original with File.delete if it's a "move" operation). To do this with the greatest efficiency, use the FileChannel.transferTo or FileChannel.transferFrom methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.

How to utilize date add function in Google spreadsheet?

Using pretty much the same approach as used by Burnash, for the final result you can use ...

=regexextract(A1,"[0-9]+")+A2

where A1 houses the string with text and number and A2 houses the date of interest

What's the difference between display:inline-flex and display:flex?

You need a bit more information so that the browser knows what you want. For instance, the children of the container need to be told "how" to flex.

Updated Fiddle

I've added #wrapper > * { flex: 1; margin: auto; } to your CSS and changed inline-flex to flex, and you can see how the elements now space themselves out evenly on the page.

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

How to communicate between iframe and the parent site?

With different domains, it is not possible to call methods or access the iframe's content document directly.

You have to use cross-document messaging.

For example in the top window:

 myIframe.contentWindow.postMessage('hello', '*');

and in the iframe:

window.onmessage = function(e){
    if (e.data == 'hello') {
        alert('It works!');
    }
};

If you are posting message from iframe to parent window

window.top.postMessage('hello', '*')

Call a function from another file?

If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:

Let's say you have following package structure in your python project:

Python package and file structure

in - com.my.func.DifferentFunction python file you have some function, like:

def add(arg1, arg2):
    return arg1 + arg2

def sub(arg1, arg2) :
    return arg1 - arg2

def mul(arg1, arg2) :
    return arg1 * arg2

And you want to call different functions from Example3.py, then following way you can do it:

Define import statement in Example3.py - file for import all function

from com.my.func.DifferentFunction import *

or define each function name which you want to import

from com.my.func.DifferentFunction import add, sub, mul

Then in Example3.py you can call function for execute:

num1 = 20
num2 = 10

print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))

Output:

 add :  30

 sub :  10

 mul :  200

how to convert object into string in php

There is an object serialization module, with the serialize function you can serialize any object.

Append a Lists Contents to another List C#

Here is my example:

    private List<int> m_machinePorts = new List<int>();

    public List<int> machinePorts
    {
        get { return m_machinePorts; }
    }

    Init()
    {
        // Custom function to get available ethernet ports
        List<int> localEnetPorts = _Globals.GetAvailableEthernetPorts();

        // Custome function to get available serial ports
        List<int> localPorts = _Globals.GetAvailableSerialPorts();

        // Build Available port list 
        m_machinePorts.AddRange(localEnetPorts);
        m_machinePorts.AddRange(localPorts);
     }

What is the use of "assert"?

Assertions are a systematic way to check that the internal state of a program is as the programmer expected, with the goal of catching bugs. See the example below.

>>> number = input('Enter a positive number:')
Enter a positive number:-1
>>> assert (number > 0), 'Only positive numbers are allowed!'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Only positive numbers are allowed!
>>> 

Print execution time of a shell command

For a line-by-line delta measurement, try gnonom.

It is a command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.

Piping anything to gnomon will prepend a timestamp to each line, indicating how long that line was the last line in the buffer--that is, how long it took the next line to appear. By default, gnomon will display the seconds elapsed between each line, but that is configurable.

gnomon demo

How to install easy_install in Python 2.7.1 on Windows 7

That tool is part of the setuptools (now called Distribute) package. Install Distribute. Of course you'll have to fetch that one manually.

http://pypi.python.org/pypi/distribute#installation-instructions

Access HTTP response as string in Go

The method you're using to read the http body response returns a byte slice:

func ReadAll(r io.Reader) ([]byte, error)

official documentation

You can convert []byte to a string by using

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

History or log of commands executed in Git

A log of your commands may be available in your shell history.

history

If seeing the list of executed commands fly by isn't for you, export the list into a file.

history > path/to/file

You can restrict the exported dump to only show commands with "git" in them by piping it with grep

history | grep "git " > path/to/file

The history may contain lines formatted as such

518  git status -s
519  git commit -am "injects sriracha to all toppings, as required"

Using the number you can re-execute the command with an exclamation mark

$ !518
git status -s

How to define the css :hover state in a jQuery selector?

You can try this:

$(".myclass").mouseover(function() {
    $(this).find(" > div").css("background-color","red");
}).mouseout(function() {
    $(this).find(" > div").css("background-color","transparent");
});

DEMO

Getting All Variables In Scope

As everyone noticed: you can't. But you can create a obj and assign every var you declare to that obj. That way you can easily check out your vars:

var v = {}; //put everything here

var f = function(a, b){//do something
}; v.f = f; //make's easy to debug
var a = [1,2,3];
v.a = a;
var x = 'x';
v.x = x;  //so on...

console.log(v); //it's all there

Scroll to bottom of div with Vue.js

For those that haven't found a working solution above, I believe I have a working one. My specific use case was that I wanted to scroll to the bottom of a specific div - in my case a chatbox - whenever a new message was added to the array.

const container = this.$el.querySelector('#messagesCardContent');
        this.$nextTick(() => {
          // DOM updated
          container.scrollTop = container.scrollHeight;
        });

I have to use nextTick as we need to wait for the dom to update from the data change before doing the scroll!

I just put the above code in a watcher for the messages array, like so:

messages: {
      handler() {
        // this scrolls the messages to the bottom on loading data
        const container = this.$el.querySelector('#messagesCard');
        this.$nextTick(() => {
          // DOM updated
          container.scrollTop = container.scrollHeight;
        });
      },
      deep: true,
    }, 

Function return value in PowerShell

Luke's description of the function results in these scenarios seems to be right on. I only wish to understand the root cause and the PowerShell product team would do something about the behavior. It seems to be quite common and has cost me too much debugging time.

To get around this issue I've been using global variables rather than returning and using the value from the function call.

Here's another question on the use of global variables: Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

How to install JSON.NET using NuGet?

You can do this a couple of ways.

Via the "Solution Explorer"

  1. Simply right-click the "References" folder and select "Manage NuGet Packages..."
  2. Once that window comes up click on the option labeled "Online" in the left most part of the dialog.
  3. Then in the search bar in the upper right type "json.net"
  4. Click "Install" and you're done.

Via the "Package Manager Console"

  1. Open the console. "View" > "Other Windows" > "Package Manager Console"
  2. Then type the following:
    Install-Package Newtonsoft.Json

For more info on how to use the "Package Manager Console" check out the nuget docs.

How to install XNA game studio on Visual Studio 2012?

I found another issue, for some reason if the extensions are cached in the local AppData folder, the XNA extensions never get loaded.

You need to remove the files extensionSdks.en-US.cache and extensions.en-US.cache from the %LocalAppData%\Microsoft\VisualStudio\11.0\Extensions folder. These files are rebuilt the next time you launch

If you need access to the Visual Studio startup log to debug what's happening, run devenv.exe /log command from the C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE directory (assuming you are on a 64 bit machine). The log file generated is located here:

%AppData%\Microsoft\VisualStudio\11.0\ActivityLog.xml

how to get right offset of an element? - jQuery

There's a native DOM API that achieves this out of the box — getBoundingClientRect:

document.querySelector("#whatever").getBoundingClientRect().right

What is the difference between UTF-8 and ISO-8859-1?

From another perspective, files that both unicode and ascii encodings fail to read because they have a byte 0xc0 in them, seem to get read by iso-8859-1 properly. The caveat is that the file shouldn't have unicode characters in it of course.

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

I want to give an example which others haven't mentioned

* can also unpack a generator

An example from Python3 Document

x = [1, 2, 3]
y = [4, 5, 6]

unzip_x, unzip_y = zip(*zip(x, y))

unzip_x will be [1, 2, 3], unzip_y will be [4, 5, 6]

The zip() receives multiple iretable args, and return a generator.

zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))

Redirect Windows cmd stdout and stderr to a single file

You want:

dir > a.txt 2>&1

The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL, more explanation and examples on MSDN.

How do I get client IP address in ASP.NET CORE?

In project.json add a dependency to:

"Microsoft.AspNetCore.HttpOverrides": "1.0.0"

In Startup.cs, in the Configure() method add:

  app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor |
            ForwardedHeaders.XForwardedProto
        });  

And, of course:

using Microsoft.AspNetCore.HttpOverrides;

Then, I could get the ip by using:

Request.HttpContext.Connection.RemoteIpAddress

In my case, when debugging in VS I got always IpV6 localhost, but when deployed on an IIS I got always the remote IP.

Some useful links: How do I get client IP address in ASP.NET CORE? and RemoteIpAddress is always null

The ::1 is maybe because of:

Connections termination at IIS, which then forwards to Kestrel, the v.next web server, so connections to the web server are indeed from localhost. (https://stackoverflow.com/a/35442401/5326387)

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

this may be a simpler approach:

(DesiredFigure).get_figure().savefig('figure_name.png')

i.e.

dfcorr.hist(bins=50).get_figure().savefig('correlation_histogram.png')

What is a good way to handle exceptions when trying to read a file in python?

I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open, then open has to be wrapped in a try. If the call to open is in the header of a with, then the with has to be in a try to catch the exception. There's no way around that.

So the answer is either: "Tim's way" or "No, you're doing it correctly.".


Previous unhelpful answer to which all the comments refer:

import os

if os.path.exists(fName):
   with open(fName, 'rb') as f:
       try:
           # do stuff
       except : # whatever reader errors you care about
           # handle error

How to close a Java Swing application from the code

Your JFrame default close action can be set to "DISPOSE_ON_CLOSE" instead of EXIT_ON_CLOSE (why people keep using EXIT_ON_CLOSE is beyond me).

If you have any undisposed windows or non-daemon threads, your application will not terminate. This should be considered a error (and solving it with System.exit is a very bad idea).

The most common culprits are java.util.Timer and a custom Thread you've created. Both should be set to daemon or must be explicitly killed.

If you want to check for all active frames, you can use Frame.getFrames(). If all Windows/Frames are disposed of, then use a debugger to check for any non-daemon threads that are still running.

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

apache not accepting incoming connections from outside of localhost

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

# setsebool -P httpd_can_network_connect=1

How to push both value and key into PHP array

array_push($GET, $GET['one']=1);

It works for me.

Case insensitive string compare in LINQ-to-SQL

As you say, there are some important differences between ToUpper and ToLower, and only one is dependably accurate when you're trying to do case insensitive equality checks.

Ideally, the best way to do a case-insensitive equality check would be:

String.Equals(row.Name, "test", StringComparison.OrdinalIgnoreCase)

NOTE, HOWEVER that this does not work in this case! Therefore we are stuck with ToUpper or ToLower.

Note the OrdinalIgnoreCase to make it security-safe. But exactly the type of case (in)sensitive check you use depends on what your purposes is. But in general use Equals for equality checks and Compare when you're sorting, and then pick the right StringComparison for the job.

Michael Kaplan (a recognized authority on culture and character handling such as this) has relevant posts on ToUpper vs. ToLower:

He says "String.ToUpper – Use ToUpper rather than ToLower, and specify InvariantCulture in order to pick up OS casing rules"

Cannot deserialize the current JSON array (e.g. [1,2,3])

You can use this to solve your problem:

private async void btn_Go_Click(object sender, RoutedEventArgs e)
{
    HttpClient webClient = new HttpClient();
    Uri uri = new Uri("http://www.school-link.net/webservice/get_student/?id=" + txtVCode.Text);
    HttpResponseMessage response = await webClient.GetAsync(uri);
    var jsonString = await response.Content.ReadAsStringAsync();
    var _Data = JsonConvert.DeserializeObject <List<Student>>(jsonString);
    foreach (Student Student in _Data)
    {
        tb1.Text = Student.student_name;
    }
}

Android- create JSON Array and JSON Object

You can create a a method and pass paramters to it and get the json as a response.

  private JSONObject jsonResult(String Name,int id, String curriculum) throws JSONException {
        JSONObject json = null;
        json = new JSONObject("{\"" + "Name" + "\":" + "\"" + Name+ "\""
            + "," + "\"" + "Id" + "\":" + id + "," + "\"" + "Curriculum"
            + "\":" + "\"" + curriculum+ "\"" + "}");
        return json;
      }

I hope this will help you.

Convert Map to JSON using Jackson

If you're using jackson, better to convert directly to ObjectNode.

//not including SerializationFeatures for brevity
static final ObjectMapper mapper = new ObjectMapper();

//pass it your payload
public static ObjectNode convObjToONode(Object o) {
    StringWriter stringify = new StringWriter();
    ObjectNode objToONode = null;

    try {
        mapper.writeValue(stringify, o);
        objToONode = (ObjectNode) mapper.readTree(stringify.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(objToONode);
    return objToONode;
}

How to create a new database after initally installing oracle database 11g Express Edition?

"How do I create an initial database ?"

You created a database when you installed XE. At some point the installation process prompted you to enter a password for the SYSTEM account. Use that to connect to the XE database using the SQL commandline on the application menu.

The XE documentation is online and pretty helpful. Find it here.

It's worth mentioning that 11g XE has several limitations, one of which is only one database per server. So using the pre-installed database is the sensible option.

Auto insert date and time in form input field?

It sounds like you are going to be storing the value that input field contains after the form is submitted, which means you are using a scripting language. I would use it instead of JavaScript as most scripting languages have better time/date formatting options. In PHP you could do something like this:

<input id="date" name="date" value="<?php echo date("M j, Y - g:i"); ?>"/>

Which would fill the field with "Jun 16, 2009 - 8:58"

Autowiring fails: Not an managed Type

You get the same exception when you pass the incorrect Entity object to the CrudRepository in the repository class.

public interface XYZRepository extends CrudRepository<IncorrectEntityClass, Long>

How to extract duration time from ffmpeg output?

I would just do this in C++ with a text file and extract the tokens. Why? I am not a linux terminal expert like the others.
To set it up I would do this in Linux..

ffmpeg -i 2>&1 | grep "" > mytext.txt

and then run some C++ app to get the data needed. Maybe extract all the important values and reformat it for further processing by using tokens. I will just have to work on my own solution and people will just make fun of me because I am a linux newbie and I do not like scripting too much.

Parsing XML with namespace in Python via 'ElementTree'

Note: This is an answer useful for Python's ElementTree standard library without using hardcoded namespaces.

To extract namespace's prefixes and URI from XML data you can use ElementTree.iterparse function, parsing only namespace start events (start-ns):

>>> from io import StringIO
>>> from xml.etree import ElementTree
>>> my_schema = u'''<rdf:RDF xml:base="http://dbpedia.org/ontology/"
...     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...     xmlns:owl="http://www.w3.org/2002/07/owl#"
...     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
...     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
...     xmlns="http://dbpedia.org/ontology/">
... 
...     <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
...         <rdfs:label xml:lang="en">basketball league</rdfs:label>
...         <rdfs:comment xml:lang="en">
...           a group of sports teams that compete against each other
...           in Basketball
...         </rdfs:comment>
...     </owl:Class>
... 
... </rdf:RDF>'''
>>> my_namespaces = dict([
...     node for _, node in ElementTree.iterparse(
...         StringIO(my_schema), events=['start-ns']
...     )
... ])
>>> from pprint import pprint
>>> pprint(my_namespaces)
{'': 'http://dbpedia.org/ontology/',
 'owl': 'http://www.w3.org/2002/07/owl#',
 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
 'xsd': 'http://www.w3.org/2001/XMLSchema#'}

Then the dictionary can be passed as argument to the search functions:

root.findall('owl:Class', my_namespaces)

Who sets response content-type in Spring MVC (@ResponseBody)

You can use produces to indicate the type of the response you are sending from the controller. This "produces" keyword will be most useful in ajax request and was very helpful in my project

@RequestMapping(value = "/aURLMapping.htm", method = RequestMethod.GET, produces = "text/html; charset=utf-8") 

public @ResponseBody String getMobileData() {

}

What is the meaning of "POSIX"?

A specification (blueprint) about how to make an OS compatible with late UNIX OS (may God bless him!). This is why macOS and GNU/Linux have very similar terminal command lines, GUI's, libraries, etc. Because they both were designed according to POSIX blueprint.

POSIX does not tell engineers and programmers how to code but what to code.

Docker expose all ports or range of ports from 7000 to 8000

Since Docker 1.5 you can now expose a range of ports to other linked containers using:

The Dockerfile EXPOSE command:

EXPOSE 7000-8000

or The Docker run command:

docker run --expose=7000-8000

Or instead you can publish a range of ports to the host machine via Docker run command:

docker run -p 7000-8000:7000-8000

How to hide scrollbar in Firefox?

I tried everything and what worked best for my solution was to always have the vertical scrollbar show, and then add some negative margin to hide it.

This worked for IE11, FF60.9 and Chrome 80

body {
  -ms-overflow-style: none; /** IE11 */
  overflow-y: scroll;
  overflow-x: hidden;
  margin-right: -20px;
}

How to run a single test with Mocha?

Depending on your usage pattern, you might just like to use only. We use the TDD style; it looks like this:

test.only('Date part of valid Partition Key', function (done) {
    //...
}

Only this test will run from all the files/suites.

Get absolute path to workspace directory in Jenkins Pipeline plugin

For me WORKSPACE was a valid property of the pipeline itself. So when I handed over this to a Groovy method as parameter context from the pipeline script itself, I was able to access the correct value using "... ${context.WORKSPACE} ..."

(on Jenkins 2.222.3, Build Pipeline Plugin 1.5.8, Pipeline: Nodes and Processes 2.35)

The SQL OVER() clause - when and why is it useful?

  • Also Called Query Petition Clause.
  • Similar to the Group By Clause

    • break up data into chunks (or partitions)
    • separate by partition bounds
    • function performs within partitions
    • re-initialised when crossing parting boundary

Syntax:
function (...) OVER (PARTITION BY col1 col3,...)

  • Functions

    • Familiar functions such as COUNT(), SUM(), MIN(), MAX(), etc
    • New Functions as well (eg ROW_NUMBER(), RATION_TO_REOIRT(), etc.)


More info with example : http://msdn.microsoft.com/en-us/library/ms189461.aspx

How to Compare two Arrays are Equal using Javascript?

A more modern version:

function arraysEqual(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every((el, ix) => el === b[ix]);
}

Coercing non-array arguments to empty arrays stops a.every() from exploding.

If you just want to see if the arrays have the same set of elements then you can use Array.includes():

function arraysContainSame(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every(el => b.includes(el));
}

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

How to .gitignore all files/folder in a folder, but not the folder itself?

Put this .gitignore into the folder, then git add .gitignore.

*
*/
!.gitignore

The * line tells git to ignore all files in the folder, but !.gitignore tells git to still include the .gitignore file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore it needs.

Edit: May be obvious but also add */ to the .gitignore to also ignore subfolders.

How can you use php in a javascript function

In the above given code

assign the php value to javascript variable.

<html>
<?php
 $num = 1;
 echo $num;
?>
  <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
  <br>
  <script>
   var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var             numeric 
  function Inc()
   {
     numeric = eVal(numeric) + 1;
     alert("Increamented value: "+numeric);
   }
  </script>
</html>

One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.

How to use <md-icon> in Angular Material?

All md- prefixes are now mat- prefixes as of time of writing this!

Put this in your html head:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Import in our module:

import { MatIconModule } from '@angular/material';

Use in your code:

<mat-icon>face</mat-icon>

Here is the latest documentation:

https://material.angular.io/components/icon/overview

How to get VM arguments from inside of Java application?

I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean's list, you get the full list of arguments.

Here's the SSCCE:

import java.util.*;
import java.lang.management.ManagementFactory;

class main {
  public static void main(final String[] args) {
    System.out.println(fullVMArguments());
  }

  static String fullVMArguments() {
    String name = javaVmName();
    return (contains(name, "Server") ? "-server "
      : contains(name, "Client") ? "-client " : "")
      + joinWithSpace(vmArguments());
  }

  static List<String> vmArguments() {
    return ManagementFactory.getRuntimeMXBean().getInputArguments();
  }

  static boolean contains(String s, String b) {
    return s != null && s.indexOf(b) >= 0;
  }

  static String javaVmName() {
    return System.getProperty("java.vm.name");
  }

  static String joinWithSpace(Collection<String> c) {
    return join(" ", c);
  }

  public static String join(String glue, Iterable<String> strings) {
    if (strings == null) return "";
    StringBuilder buf = new StringBuilder();
    Iterator<String> i = strings.iterator();
    if (i.hasNext()) {
      buf.append(i.next());
      while (i.hasNext())
        buf.append(glue).append(i.next());
    }
    return buf.toString();
  }
}

Could be made shorter if you want the arguments in a List<String>.

Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.

Splitting applicationContext to multiple files

Mike Nereson has this to say on his blog at:

http://blog.codehangover.com/load-multiple-contexts-into-spring/

There are a couple of ways to do this.

1. web.xml contextConfigLocation

Your first option is to load them all into your Web application context via the ContextConfigLocation element. You’re already going to have your primary applicationContext here, assuming you’re writing a web application. All you need to do is put some white space between the declaration of the next context.

  <context-param>
      <param-name> contextConfigLocation </param-name>
      <param-value>
          applicationContext1.xml
          applicationContext2.xml
      </param-value>
  </context-param>

  <listener>
      <listener-class>
          org.springframework.web.context.ContextLoaderListener
      </listener-class>
  </listener>

The above uses carriage returns. Alternatively, yo could just put in a space.

  <context-param>
      <param-name> contextConfigLocation </param-name>
      <param-value> applicationContext1.xml applicationContext2.xml </param-value>
  </context-param>

  <listener>
      <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>
  </listener>

2. applicationContext.xml import resource

Your other option is to just add your primary applicationContext.xml to the web.xml and then use import statements in that primary context.

In applicationContext.xml you might have…

  <!-- hibernate configuration and mappings -->
  <import resource="applicationContext-hibernate.xml"/>

  <!-- ldap -->
  <import resource="applicationContext-ldap.xml"/>

  <!-- aspects -->
  <import resource="applicationContext-aspects.xml"/>

Which strategy should you use?

1. I always prefer to load up via web.xml.

Because , this allows me to keep all contexts isolated from each other. With tests, we can load just the contexts that we need to run those tests. This makes development more modular too as components stay loosely coupled, so that in the future I can extract a package or vertical layer and move it to its own module.

2. If you are loading contexts into a non-web application, I would use the import resource.

Entity Framework Query for inner join

from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s

Where db is your DbContext. Generated query will look like (sample for EF6):

SELECT [Extent1].[Id] AS [Id]
       -- other fields from Services table
FROM [dbo].[Services] AS [Extent1]
INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]
    ON [Extent1].[Id] = [Extent2].[ServiceId]
WHERE [Extent2].[LocationId] = 1

Specifying colClasses in the read.csv

If you want to refer to names from the header rather than column numbers, you can use something like this:

fname <- "test.csv"
headset <- read.csv(fname, header = TRUE, nrows = 10)
classes <- sapply(headset, class)
classes[names(classes) %in% c("time")] <- "character"
dataset <- read.csv(fname, header = TRUE, colClasses = classes)

SQL Server: Best way to concatenate multiple columns?

Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT() function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.

An alternative:

SELECT '1'+'2'+'3'

This approach requires non-string values to be cast/converted to strings, as well as NULL handling via ISNULL() or COALESCE():

SELECT  ISNULL(CAST(Col1 AS VARCHAR(50)),'')
      + COALESCE(CONVERT(VARCHAR(50),Col2),'')

php is null or empty?

What you're looking for is:

if($variable === NULL) {...}

Note the ===.
When use ==, as you did, PHP treats NULL, false, 0, the empty string, and empty arrays as equal.

How to Debug Variables in Smarty like in PHP var_dump()

In new Smarty it is:

<pre>
{var_dump($variable)}
</pre>

Execute cmd command from VBScript

Can also invoke oShell.Exec in order to be able to read STDIN/STDOUT/STDERR responses. Perfect for error checking which it seems you're doing with your sanity .BAT.

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

jQuery get the location of an element relative to window

This sounds more like you want a tooltip for the link selected. There are many jQuery tooltips, try out jQuery qTip. It has a lot of options and is easy to change the styles.

Otherwise if you want to do this yourself you can use the jQuery .position(). More info about .position() is on http://api.jquery.com/position/

$("#element").position(); will return the current position of an element relative to the offset parent.

There is also the jQuery .offset(); which will return the position relative to the document.

Correct use of transactions in SQL Server

At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.

MySQL export into outfile : CSV escaping chars

What happens if you try the following?

Instead of your double REPLACE statement, try:

REPLACE(IFNULL(ts.description, ''),'\r\n', '\n')

Also, I think it should be LINES TERMINATED BY '\r\n' instead of just '\n'

Javascript: Call a function after specific time period

You can use JavaScript Timing Events to call function after certain interval of time:

This shows the alert box after 3 seconds:

setInterval(function(){alert("Hello")},3000);

You can use two method of time event in javascript.i.e.

  1. setInterval(): executes a function, over and over again, at specified time intervals
  2. setTimeout() : executes a function, once, after waiting a specified number of milliseconds

In Subversion can I be a user other than my login name?

Using Subversion with either the Apache module or svnserve. I've been able to perform operations as multiple users using --username.

Each time you invoke a Subversion command as a 'new' user, your $HOME/.subversion/auth/<authentication-method>/ directory will have a new entry cached for that user (assuming you are able to authenticate with the correct password or authentication method for the server you are contacting as that particular user).

To switch from vertical split to horizontal split fast in Vim

Vim mailing list says (re-formatted for better readability):

To change two vertically split windows to horizonally split

Ctrl-w t Ctrl-w K

Horizontally to vertically:

Ctrl-w t Ctrl-w H

Explanations:

Ctrl-w t makes the first (topleft) window current

Ctrl-w K moves the current window to full-width at the very top

Ctrl-w H moves the current window to full-height at far left

Note that the t is lowercase, and the K and H are uppercase.

Also, with only two windows, it seems like you can drop the Ctrl-w t part because if you're already in one of only two windows, what's the point of making it current?

Get the directory from a file path in java (android)

A better way, use getParent() from File Class..

String a="/root/sdcard/Pictures/img0001.jpg"; // A valid file path 
File file = new File(a); 
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null

http://developer.android.com/reference/java/io/File.html#getParent%28%29

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

How to add label in chart.js for pie chart

Use ChartNew.js instead of Chart.js

...

So, I have re-worked Chart.js. Most of the changes, are associated to requests in "GitHub" issues of Chart.js.

And here is a sample http://jsbin.com/lakiyu/2/edit

var newopts = {
    inGraphDataShow: true,
    inGraphDataRadiusPosition: 2,
    inGraphDataFontColor: 'white'
}
var pieData = [
    {
        value: 30,
        color: "#F38630",
    },
    {
       value: 30,
       color: "#F34353",
    },
    {
        value: 30,
        color: "#F34353",
    }
]
var pieCtx = document.getElementById('pieChart').getContext('2d');
new Chart(pieCtx).Pie(pieData, newopts);

It even provides a GUI editor http://charts.livegap.com/

So sweet.

How to debug when Kubernetes nodes are in 'Not Ready' state

Steps to debug:-

In case you face any issue in kubernetes, first step is to check if kubernetes self applications are running fine or not.

Command to check:- kubectl get pods -n kube-system

If you see any pod is crashing, check it's logs

if getting NotReady state error, verify network pod logs.

if not able to resolve with above, follow below steps:-

  1. kubectl get nodes # Check which node is not in ready state

  2. kubectl describe node nodename #nodename which is not in readystate

  3. ssh to that node

  4. execute systemctl status kubelet # Make sure kubelet is running

  5. systemctl status docker # Make sure docker service is running

  6. journalctl -u kubelet # To Check logs in depth

Most probably you will get to know about error here, After fixing it reset kubelet with below commands:-

  1. systemctl daemon-reload
  2. systemctl restart kubelet

In case you still didn't get the root cause, check below things:-

  1. Make sure your node has enough space and memory. Check for /var directory space especially. command to check: -df -kh, free -m

  2. Verify cpu utilization with top command. and make sure any process is not taking an unexpected memory.

How can I get just the first row in a result set AFTER ordering?

In 12c, here's the new way:

select bla
  from bla
 where bla
 order by finaldate desc
 fetch first 1 rows only; 

How nice is that!

making a paragraph in html contain a text from a file

I would use javascript for this.

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
  if (txtFile.readyState === 4 && txtFile.status == 200) {
     allText = txtFile.responseText;
  }
document.getElementById('your div id').innerHTML = allText;

This is just a code sample, would need tweaking for all browsers, etc.

How can I get LINQ to return the object which has the max value for a given property?

Or you can write your own extension method:

static partial class Extensions
{
    public static T WhereMax<T, U>(this IEnumerable<T> items, Func<T, U> selector)
    {
        if (!items.Any())
        {
            throw new InvalidOperationException("Empty input sequence");
        }

        var comparer = Comparer<U>.Default;
        T   maxItem  = items.First();
        U   maxValue = selector(maxItem);

        foreach (T item in items.Skip(1))
        {
            // Get the value of the item and compare it to the current max.
            U value = selector(item);
            if (comparer.Compare(value, maxValue) > 0)
            {
                maxValue = value;
                maxItem  = item;
            }
        }

        return maxItem;
    }
}

go to character in vim

vim +21490go script.py

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

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


Excerpt from man vim:

+{command}

-c {command}

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

Eclipse: Enable autocomplete / content assist

I am not sure if this has to be explicitly enabled anywhere..but for this to work in the first place you need to include the javadoc jar files with the related jars in your project. Then when you do a Cntrl+Space it shows autocomplete and javadocs.

How to run a makefile in Windows?

I use MinGW tool set which provides mingw32-make build tool, if you have it in your PATH system variables, in Windows Command Prompt just go into the directory containing the files and type this command:

mingw32-make -f Makefile.win

and it's done.

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

How to create a popup windows in javafx

Have you looked into ControlsFx Popover control.


import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;

private PopOver item;

final Scene scene = addItemButton.getScene();

final Point2D windowCoord = new Point2D(scene.getWindow()
        .getX(), scene.getWindow().getY());

final Point2D sceneCoord = new Point2D(scene.getX(), scene.
                getY());

final Point2D nodeCoord = addItemButton.localToScene(0.0,
                        0.0);
final double clickX = Math.round(windowCoord.getX()
    + sceneCoord.getY() + nodeCoord.getX());

final double clickY = Math.round(windowCoord.getY()
        + sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);                            
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);

This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.

Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.

Python float to int conversion

>>> x = 2.51
>>> x*100
250.99999999999997

the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.

you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library http://code.google.com/p/mpmath/ :),

How can I convert an HTML element to a canvas element?

You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>'s and <ol>'s and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/

javascript: calculate x% of a number

Best thing is to memorize balance equation in natural way.

Amount / Whole = Percentage / 100

usually You have one variable missing, in this case it is Amount

Amount / 10000 = 35.8 / 100

then you have high school math (proportion) to multiple outer from both sides and inner from both sides.

Amount * 100 = 358 000

Amount = 3580

It works the same in all languages and on paper. JavaScript is no exception.

Javascript checkbox onChange

function calc()
{
  if (document.getElementById('xxx').checked) 
  {
      document.getElementById('totalCost').value = 10;
  } else {
      calculate();
  }
}

HTML

<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

Python 2

The error is caused because ElementTree did not expect to find non-ASCII strings set the XML when trying to write it out. You should use Unicode strings for non-ASCII instead. Unicode strings can be made either by using the u prefix on strings, i.e. u'€' or by decoding a string with mystr.decode('utf-8') using the appropriate encoding.

The best practice is to decode all text data as it's read, rather than decoding mid-program. The io module provides an open() method which decodes text data to Unicode strings as it's read.

ElementTree will be much happier with Unicodes and will properly encode it correctly when using the ET.write() method.

Also, for best compatibility and readability, ensure that ET encodes to UTF-8 during write() and adds the relevant header.

Presuming your input file is UTF-8 encoded (0xC2 is common UTF-8 lead byte), putting everything together, and using the with statement, your code should look like:

with io.open('myText.txt', "r", encoding='utf-8') as f:
    data = f.read()

root = ET.Element("add")
doc = ET.SubElement(root, "doc")

field = ET.SubElement(doc, "field")
field.set("name", "text")
field.text = data

tree = ET.ElementTree(root)
tree.write("output.xml", encoding='utf-8', xml_declaration=True)

Output:

<?xml version='1.0' encoding='utf-8'?>
<add><doc><field name="text">data€</field></doc></add>

Delete empty lines using sed

With help from the accepted answer here and the accepted answer above, I have used:

$ sed 's/^ *//; s/ *$//; /^$/d; /^\s*$/d' file.txt > output.txt

`s/^ *//`  => left trim
`s/ *$//`  => right trim
`/^$/d`    => remove empty line
`/^\s*$/d` => delete lines which may contain white space

This covers all the bases and works perfectly for my needs. Kudos to the original posters @Kent and @kev

Must declare the scalar variable

This will occur in SQL Server as well if you don't run all of the statements at once. If you are highlighting a set of statements and executing the following:

DECLARE @LoopVar INT
SET @LoopVar = (SELECT COUNT(*) FROM SomeTable)

And then try to highlight another set of statements such as:

PRINT 'LoopVar is: ' + CONVERT(NVARCHAR(255), @LoopVar)

You will receive this error.

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified his example to do this here: http://jsfiddle.net/QLfMU/116/

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

Gradients in Internet Explorer 9

The code I use for all browser gradients:

background: #0A284B;
background: -webkit-gradient(linear, left top, left bottom, from(#0A284B), to(#135887));
background: -webkit-linear-gradient(#0A284B, #135887);
background: -moz-linear-gradient(top, #0A284B, #135887);
background: -ms-linear-gradient(#0A284B, #135887);
background: -o-linear-gradient(#0A284B, #135887);
background: linear-gradient(#0A284B, #135887);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0A284B', endColorstr='#135887');
zoom: 1;

You will need to specify a height or zoom: 1 to apply hasLayout to the element for this to work in IE.


Update:

Here is a LESS Mixin (CSS) version for all you LESS users out there:

.gradient(@start, @end) {
    background: mix(@start, @end, 50%);
    filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorStr="@start~", EndColorStr="@end~")";
    background: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end));
    background: -webkit-linear-gradient(@start, @end);
    background: -moz-linear-gradient(top, @start, @end);
    background: -ms-linear-gradient(@start, @end);
    background: -o-linear-gradient(@start, @end);
    background: linear-gradient(@start, @end);
    zoom: 1;
}

Show Hide div if, if statement is true

<?php
$divStyle=''; // show div

// add condition
if($variable == '1'){
  $divStyle='style="display:none;"'; //hide div
}

print'<div '.$divStyle.'>Div to hide</div>';
?>

How do I write a batch script that copies one directory to another, replaces old files?

It seems that the latest function for this in windows 7 is robocopy.

Usage example:

robocopy <source> <destination> /e /xf <file to exclude> <another file>

/e copies subdirectories including empty ones, /xf excludes certain files from being copied.

More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx